我正在制作一个使用声音效果的应用。我想知道我是如何检测声音何时播放并触发事件的。
我试过这个:
player = new MediaPlayer();
if (player != null) {
player.reset();
player.release();
}
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
sonar.setBackgroundResource(R.drawable.sonar_off);
stopPlay();
}
});
if(state==1){
player = MediaPlayer.create(this, R.raw.sonar_slow);
}else if(state==2){
player = MediaPlayer.create(this, R.raw.sonar_medium);
}else if(state==3){
player = MediaPlayer.create(this, R.raw.sonar_fast);
}
try{
player.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.start();
答案 0 :(得分:10)
您可以将OnCompleteListener()设置为播放器对象。它的代码是:
mPlayer.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp)
{
"your code comes here"
}
});
此处mPlayer是当前正在运行的MediaPlayer的对象。
答案 1 :(得分:0)
有多种方式播放声音,假设您使用MediaPlayer类,则可以注册MediaPlayer.OnCompletionListener