在我的应用程序中,我需要在不同时刻播放声音并等待它结束然后再做其他事情。现在我有这个播放声音的代码:
private MediaPlayer mPlayer = null;
private boolean playSound(){
mPlayer = new MediaPlayer();
try{
mPlayer.setDataSource(openFileInput(fileName).getFD());
mPlayer.prepare();
mPlayer.start();
} catch (Exception e){
e.printStackTrace();
Log.e("player", "error playing sound: "+fileName);
return false;
}
while(mPlayer.isPlaying());
mPlayer.release();
mPlayer = null;
return true;
}
它没有按照我的预期工作:在播放声音之前更改图像时,声音播放后发生了变化(我想这是针对线程队列或类似的事情)
我不知道这是一个糟糕的解决方案,还是我的案例有更好的解决方案:
答案 0 :(得分:0)
您应该实现一个完成侦听器:
public class myclass extends .... implements OnCompletionListener, ... {
private int nextAction; // not the smatest solution, but good enough :)
...
private boolean playSound(next){
nextAction = next;
mPlayer = new MediaPlayer();
try{
mPlayer.setDataSource(openFileInput(fileName).getFD());
mPlayer.prepare();
mPlayer.setOnCompletionListener(this);
mPlayer.start();
} catch (Exception e){
e.printStackTrace();
Log.e("player", "error playing sound: "+fileName);
return false;
}
@Override
public void onCompletion(MediaPlayer mp) {
// do your stuff, destroy the mplayer, if needed
switch(nextAction){
case ACTION1: ...; break;
case ACTION2: ...; break; //..and so on
}
}