Sound does not stop playing in Android - android

My app displays video and images interchangeably. When images are displayed music is played in the background and when video is played the music should stop playing. The problem is the music sometimes does not stop playing even though I am calling stop() function of the media player. Any help is appreciated thanks in advance. The code is as follows -
public class Standee implements Runnable, OnCompletionListener {
private Vector<File> files;
private Vector<String> timings;
private Handler h;
private VideoView video;
private ImageView image;
private Context ctx;
private int i;
private MediaPlayer player;
public MediaPlayer getMediaPlayer() {
return player;
}
public Standee(Context ctx, VideoView video, ImageView image) {
this.video = video;
this.image = image;
this.ctx = ctx;
i = 0;
h = new Handler();
files = new Vector<File>();
timings = new Vector<String>();
player = MediaPlayer.create(ctx, R.raw.background);
try {
FileReader fr = new FileReader(ConfigLoader.BETA_PATH + "media.tmr");
BufferedReader br = new BufferedReader(fr);
String s;
while ((s = br.readLine()) != null) {
String[] data = s.split(";");
files.add(new File(ConfigLoader.BETA_PATH + data[0]));
timings.add(data[1]);
}
br.close();
video.setOnCompletionListener(this);
video.setMediaController(null);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onCompletion(MediaPlayer arg0) {
h.removeCallbacks(this);
i++;
if (i >= files.size())
i = 0;
run();
}
#Override
public void run() {
if (files.elementAt(i).getAbsolutePath().endsWith(".jpg")) {
video.setVisibility(View.INVISIBLE);
image.setVisibility(View.VISIBLE);
if (video.isPlaying()) {
video.stopPlayback();
}
image.bringToFront();
player = MediaPlayer.create(ctx, R.raw.background);
try {
player.setLooping(true);
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
player.start();
showPhoto();
} else if (files.elementAt(i).getAbsolutePath().endsWith(".mp4")) {
if (player.isPlaying()) {
player.stop();
}
image.setVisibility(View.INVISIBLE);
video.setVisibility(View.VISIBLE);
video.bringToFront();
playVideo();
}
h.postDelayed(this, Integer.parseInt(timings.elementAt(i)));
i++;
if (i >= files.size())
i = 0;
}
public void start() {
h.post(this);
}
public void playVideo() {
Uri uri = Uri.parse(files.get(i).getAbsolutePath());
video.setVideoURI(uri);
video.requestFocus();
video.start();
}
public void showPhoto() {
image.setImageBitmap(BitmapFactory.decodeFile(files.elementAt(i)
.getAbsolutePath()));
}
// private void fadeout(Object obj){
// ValueAnimator videoAnim=ObjectAnimator.ofFloat(obj, "alpha", 1, 0);
// videoAnim.setDuration(3000);
// videoAnim.start();
// }
//
// private void fadein(Object obj){
// ValueAnimator imageAnim=ObjectAnimator.ofFloat(obj, "alpha", 0, 1);
// imageAnim.setDuration(3000);
// imageAnim.start();
// }
}

Related

Subtitles are not displaying the when seek to backward in videoview

In my Android app videos are played with subtitles using videoview. The problem is when I'm pressing forward or dragging the seekbar subtitles are displaying, but when I'm pressing backward or dragging the seekbar backwards subtitles are not displaying. Below is the full code.
public class MainActivity extends AppCompatActivity implements View.OnTouchListener,MediaPlayer.OnInfoListener,MediaPlayer.OnSeekCompleteListener {
MediaController ctlr;
VideoView videoview;
FrameLayout playercontrolerview;
View view_full_cc;
TextView tv_subtitleText;
private static Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videoview = (VideoView) findViewById(R.id.VideoView);
tv_subtitleText=(TextView) findViewById(R.id.tv_subtitleText);
try {
// Start the MediaController
setVideoView();
preparedvideo();
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
private void setVideoView() {
ctlr = new MediaController(MainActivity.this) {
#Override
public void show() {
repositionSubtitle(true);
super.show();
}
#Override
public void hide() {
repositionSubtitle(false);
super.hide();
}
};
playercontrolerview = (FrameLayout) ctlr.getParent();
ctlr.setMediaPlayer(videoview);
ctlr.setAnchorView(videoview);
videoview.setMediaController(ctlr);
videoview.requestFocus();
}
private void preparedvideo(){
videoview.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.samplevideo));
videoview.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
try {
mp.addTimedTextSource(getSubtitleFile(R.raw.sub1), MediaPlayer.MEDIA_MIMETYPE_TEXT_SUBRIP);
int textTrackIndex = findTrackIndexFor(MediaPlayer.TrackInfo.MEDIA_TRACK_TYPE_TIMEDTEXT, mp.getTrackInfo());
if (textTrackIndex >= 0) {
try {
mp.selectTrack(textTrackIndex);
}catch (Exception e){
e.printStackTrace();
}
} else {
Log.w("subtitles", "Cannot find text track!");
}
mp.setOnTimedTextListener(new MediaPlayer.OnTimedTextListener() {
#Override
public void onTimedText(final MediaPlayer mp, final TimedText text) {
if(text!=null){
handler.post(new Runnable() {
#Override
public void run() {
try {
int seconds = mp.getCurrentPosition() / 1000;
Log.e("Subtitle", "subtitle Info " + text.getText());
tv_subtitleText.setText(text.getText());
}catch (Exception w){
w.printStackTrace();
}
}
});
}else{
Log.e("Subtitle", "subtitle Info null ");
}
}
});
}catch (Exception e){
e.printStackTrace();
}
try {
videoview.start();
}catch (Exception e){
e.printStackTrace();
}
}
});
}
public void repositionSubtitle(boolean isShown) {
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) tv_subtitleText.getLayoutParams();
if (params != null) {
if (isShown)
params.bottomMargin = 150;
else
params.bottomMargin = 0;
tv_subtitleText.setLayoutParams(params);
}
}
private int findTrackIndexFor(int mediaTrackType, MediaPlayer.TrackInfo[] trackInfo) {
int index = -1;
for (int i = 0; i < trackInfo.length; i++) {
if (trackInfo[i].getTrackType() == mediaTrackType) {
return i;
}
}
return index;
}
private String getSubtitleFile(int resId) {
String fileName = getResources().getResourceEntryName(resId);
File subtitleFile = getFileStreamPath(fileName);
if (subtitleFile.exists()) {
Log.d("subtitle", "Subtitle already exists");
return subtitleFile.getAbsolutePath();
}
Log.d("subtitle", "Subtitle does not exists, copy it from res/raw");
// Copy the file from the res/raw folder to your app folder on the
// device
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = getResources().openRawResource(resId);
outputStream = new FileOutputStream(subtitleFile, false);
copyFile(inputStream, outputStream);
return subtitleFile.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
} finally {
closeStreams(inputStream, outputStream);
}
return "";
}
private void copyFile(InputStream inputStream, OutputStream outputStream)
throws IOException {
final int BUFFER_SIZE = 1024;
byte[] buffer = new byte[BUFFER_SIZE];
int length = -1;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
}
// A handy method I use to close all the streams
private void closeStreams(Closeable... closeables) {
if (closeables != null) {
for (Closeable stream : closeables) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
videoview.getCurrentPosition();
// Collection<Caption> subtitles = srt.captions.values();
return false;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
#Override
public void onSeekComplete(MediaPlayer mp) {
}
}

Android app crashes in 5.0 and above when using MediaPlayer with url

I am developing an android app which play a mp3 songs by using a remote url. everything is working fine in android devices below api 5.0.But when starting app in samsung s5(5.1) it suddenly crashes
mu logcat is giving error "QCmediaPlayer mediaplayer is not present.Here is my code of Media Player
public class MainActivity2 extends Activity implements OnClickListener, OnPreparedListener {
private ProgressBar playSeekBar;
private final static String RADIO_STATION_URL ="https://aryaradio.s3.amazonaws.com/";
private String KEYNAME,encodedurl;
private List<String> playlistarray;
private List<MediaPlayer> mplayerList;
private ImageButton buttonPlay;
private List<S3ObjectSummary> playlist=null;
private ImageButton buttonStopPlay;
ProgressDialog progress;
URL url,currentsongurl;
private MediaPlayer player;
private AmazonS3Client mClient;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
playlistarray=new ArrayList<String>();
mplayerList=new ArrayList<MediaPlayer>();
if(isNetworkAvailable()) {
mClient = Util.getS3Client(MainActivity2.this);
initializeUIElements();
//new RefreshTask().execute();
buttonStopPlay.setVisibility(View.INVISIBLE);
} else {
new AlertDialog.Builder(MainActivity2.this)
.setTitle(getResources().getString(R.string.app_name))
.setMessage(
getResources().getString(
R.string.internet_error))
.setPositiveButton("OK", null).show();
buttonStopPlay.setVisibility(View.INVISIBLE);
buttonPlay.setVisibility(View.INVISIBLE);
}
}
private void initializeUIElements() {
buttonPlay = (ImageButton) findViewById(R.id.Play);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (ImageButton) findViewById(R.id.Stop);
buttonStopPlay.setOnClickListener(this);
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
finish();
startActivity(new Intent(MainActivity2.this, MainActivity2.class));
}
}
private void startPlaying() {
buttonPlay.setVisibility(View.INVISIBLE);
buttonStopPlay.setVisibility(View.VISIBLE);
progress = new ProgressDialog(this);
progress.setTitle("Message");
progress.setMessage("Loading Song ...");
progress.setCancelable(true);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.show();
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
progress.dismiss();
player.start();
player.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
try {
// player.setNextMediaPlayer(mplayerList.get(2));
stopPlaying();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
});
}
private void stopPlaying() {
killMediaPlayer();
initializeMediaPlayer(playlistarray);
buttonPlay.setVisibility(View.VISIBLE);
buttonStopPlay.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer(List<String> playlist) {
player = new MediaPlayer();
int noOfSongs=playlist.size();
String url = "https://aryaradio.s3.amazonaws.com/us-east-1:eb604ac1-c4e3-4226-bea8-22f214a6b0b0/RecordingArya-9459.mp3.null";
try {
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource(url);
player.setOnPreparedListener(this);
player.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
return false;
}
});
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
Log.i("Buffering", "" + percent);
}
});
}
}

AudioRecorder App crashes when I record a second time

My app breaks down when I attempt to record a second a time when I hit the stop button. I went through this code several times. I can't find the problem. I'm not sure if its my MediaRecorder or my MediaPlayer. It works the first time around. But not the second time. can anyone find the problem.
public class PatientName extends Activity implements OnClickListener {
private Button instructionsBtn;
private ImageView record;
private ImageView stop;
private MediaPlayer instructions;
private MediaPlayer namePlayer;
private MediaRecorder nameRecorder;
private String OUTPUT_FILE;
private Button play;
private Button accept;
private LinearLayout review;
private Button delete;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.patient_name);
OUTPUT_FILE = Environment.getExternalStorageDirectory() + "/namerecording.3gpp";
initializeViews();
initializeListeners();
}
public void initializeViews() {
instructionsBtn = (Button)findViewById(R.id.patient_name_instructions);
record = (ImageView)findViewById(R.id.record_name);
stop = (ImageView)findViewById(R.id.stop_name);
stop.setVisibility(View.GONE);
play = (Button)findViewById(R.id.play_name);
play.setVisibility(View.GONE);
review = (LinearLayout)findViewById(R.id.review_name);
delete = (Button)findViewById(R.id.delete_name);
accept = (Button)findViewById(R.id.accept_name);
review.setVisibility(View.GONE);
}
public void initializeListeners() {
instructionsBtn.setOnClickListener(this);
record.setOnClickListener(this);
stop.setOnClickListener(this);
play.setOnClickListener(this);
delete.setOnClickListener(this);
accept.setOnClickListener(this);
}
#Override
public void onBackPressed() {
}
public void playInstructions() {
setMaxVolume();
instructions = MediaPlayer.create(PatientName.this, R.raw.intro_instructions);
instructions.start();
instructions.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer play) {
instructions.release();
instructionsBtn.setEnabled(true);
}
});
}
public void setMaxVolume() {
AudioManager audio = (AudioManager) getSystemService(this.AUDIO_SERVICE);
int maxVolume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
audio.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, 0);
}
public void onClick(View v) {
int id = v.getId();
if (id==R.id.patient_name_instructions) {
instructionsBtn.setEnabled(false);
playInstructions();
}
if (id==R.id.record_name) {
beginRecording();
}
if (id==R.id.stop_name){
play.setVisibility(View.VISIBLE);
nameRecorder.stop();
}
if (id==R.id.play_name) {
playbackRecording();
}
if (id==R.id.delete_name){
deleteRecording();
}
if (id==R.id.accept_name) {
saveAndContinue();
}
}
private void beginRecording(){
record.setVisibility(View.GONE);
stop.setVisibility(View.VISIBLE);
File outFile = new File(OUTPUT_FILE);
if (outFile.exists()) {
outFile.delete();
}else {
nameRecorder = new MediaRecorder();
nameRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
nameRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
nameRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_WB);
nameRecorder.setOutputFile(OUTPUT_FILE);
try {
nameRecorder.prepare();
} catch (IllegalStateException e) {
Toast toast = Toast.makeText(this,"Illegal State",Toast.LENGTH_LONG);
toast.show();
e.printStackTrace();
} catch (IOException e) {
Toast toast = Toast.makeText(this,"Error Recording",Toast.LENGTH_LONG);
toast.show();
e.printStackTrace();
}
nameRecorder.start();
}
}
private void playbackRecording() {
play.setVisibility(View.GONE);
namePlayer = new MediaPlayer();
try {
namePlayer.setDataSource(OUTPUT_FILE);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
namePlayer.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
namePlayer.start();
namePlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer play) {
namePlayer.release();
nameRecorder.release();
review.setVisibility(View.VISIBLE);
}
});
}
private void deleteRecording() {
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
private void saveAndContinue() {
Intent intent = new Intent(PatientName.this, PatientLocation.class);
startActivity(intent);
}
}
Here is my logCat:
I figured out the issue. In the beginRecording method, I have an if and else statement that handles the output file. Unfortunately, the code that I had in the else statement was something that I wanted to always run no matter what.

Media Recorder record application audio

I have an application that has a few buttons that have sounds (soundPool) I need to write them down on a flash card I make it through the MediaRecorder but when I run the app and then turn on the record playing and click stop recording application crashes you do not tell me what the problem is?
I expect that in the method recordStop
public class MainActivity extends Activity {
int kickSound;
SoundPool mSoundPool;
AssetManager assets;
private MediaRecorder mediaRecorder;
private MediaPlayer mediaPlayer;
private String fileName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSoundPool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0);
assets = getAssets();
kickSound = loadSound("snare_trap.ogg");
ImageButton kick = (ImageButton)this.findViewById(R.id.imageButton1);
kick.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN){
playSound(kickSound);
}
return false;
}
});
fileName = Environment.getExternalStorageDirectory() + "/record.3gpp";
}
protected void playSound(int sound) {
if (sound > 0)
mSoundPool.play(sound, 1, 1, 1, 0, 1);
}
private int loadSound(String fileName) {
AssetFileDescriptor afd = null;
try {
afd = assets.openFd(fileName);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Couldn't load file '" + fileName + "'", Toast.LENGTH_SHORT).show();
return -1;
}
return mSoundPool.load(afd, 1);
}
public void recordStart(View v) {
try {
releaseRecorder();
File outFile = new File(fileName);
if (outFile.exists()) {
outFile.delete();
}
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(AudioManager.STREAM_MUSIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.setOutputFile(fileName);
mediaRecorder.prepare();
mediaRecorder.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void recordStop(View v) {
mediaRecorder.stop();
}
public void playStart(View v) {
try {
releasePlayer();
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(fileName);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void playStop(View v) {
if (mediaPlayer != null) {
mediaPlayer.stop();
}
}
private void releaseRecorder() {
if (mediaRecorder != null) {
mediaRecorder.release();
mediaRecorder = null;
}
}
private void releasePlayer() {
mediaPlayer.release();
mediaPlayer = null;
}
#Override
protected void onDestroy() {
super.onDestroy();
releasePlayer();
releaseRecorder();
}
}
Why are you releasing the recorder to start out with? Releasing should only be used if you don't want to access the recorder anymore. Try moving the release to the end.

Android audio delay

I have a problem when playing an mp3 in android, is something like a delay or a lag, ex:
if I have to reproduce the following: "Hello, how are you?", it only plays "how are you?" or says very low the "hello".
It happens in a ViewSonic V220 its a 22" tablet, in most of other devices, it works fine, but is in that one that seems to fail.
Its weird, becouse other apps(like youtube or media player) works fine.
This is my code, maybe i am doing something wrong:
public class SoundManager implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener {
private Parent mParent;
private MediaPlayer mediaPlayer;
String[] mp3_array;
int counter = 0;
public SoundManager(Parent parent) {
mParent = parent;
}
public void playSound(String[] url) throws IllegalArgumentException,
IllegalStateException, IOException {
mp3_array = url;
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
if (mediaPlayer.isPlaying()) {
mediaPlayer.reset();
}
mediaPlayer.setDataSource(url[0]);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.prepareAsync();
}
public void stopMediaPlayer() {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
mp3_array = null;
counter = 0;
}
}
#Override
public void onCompletion(MediaPlayer mp) {
try {
Integer c = counter;
if (mp3_array != null && counter + 1 < mp3_array.length) {
mp.reset();
mp.setOnCompletionListener(this);
mp.setOnPreparedListener(this);
counter += 1;
mp.setDataSource(mp3_array[counter]);
mediaPlayer.prepareAsync();
} else {
if (mParent != null)
mParent.invokeJs("playSoundEnded()");
mp.release();
mp = null;
mp3_array = null;
counter = 0;
}
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onPrepared(MediaPlayer mp) {
if (mParent != null)
mParent.invokeJs("playSoundStarted()");
mp.start();
}
}

Categories

Resources