I need to play several (correctly: 2) mp3 files downloaded from my assets, at the click of a button. If the button is pressed again, it is necessary to play 2 new songs, and the old ones must be stopped by immidiatelly.The process continues ... At the moment I have achieved this by stupidly creating 2 copies of mediaPlayer in two separate methods, which basically have the same body. The caller is the onTouch method, and in it I first call method 1, then sleep for 2 seconds, then the call method 2. I'm sure there must be more elegant code for this? For example, I introduced several listeners that just sit there (actually tried to do thiswork, but completely confused with illegal states everywhere). Ideally, I would like to use 1 MediaPlayer and one way to play every sound in my application.
int carouzelIndex = 0
@Override
public boolean onTouch(MotionEvent e, int scaledX, int scaledY) {
...
if (e.getAction() == MotionEvent.ACTION_UP) {
carouzelIndex++;
Assets.playMusic1("music1.ogg",false);
Thread thread = new Thread(){
public void run(){
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Assets.playMusic2("music2.ogg",false);
}
}
}
}
Now my player methods 1 and 2 (playMusic1 () and playMusic2 ()) are the same. Both launch different MediaPlayers and for shaking simplicity I write only one copy in the message
Public class Assets
MediaPlayer mediaPlayer;
public static void playMusic(String filename, boolean looping) {
AssetFileDescriptor afd = null;
Log.d("Assets", "playing music");
if (mediaPlayer == null) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setLooping(looping);
}
try {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setLooping(looping);
}
afd = GameMainActivity.assets.openFd(filename);
mediaPlayer.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
afd.close();
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
if (!mp.isPlaying())
mp.start();
}
});
mediaPlayer.setOnErrorListener(new OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
});
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mediaPlayerIsFinished = true;
mp.reset();
}
});
mediaPlayer.setOnInfoListener(new OnInfoListener() {
@Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
return false;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
source
share