检查并查看是否正在播放声音,等待它完成,然后播放另一个声音

时间:2013-08-31 03:32:31

标签: java android audio

我想要实现的是让我点击一个按钮,然后根据子串播放声音。

这是我当前按下按钮的代码:

display.setText("start");
thefull = thef.getText().toString();
for(int a=0;a<thefull.length();a++)
{
letter=thefull.substring(a,a+1);
if(letter=="m")
{
oursong = MediaPlayer.create(MainActivity.this, R.raw.m);
oursong.start();
while(oursong.isPlaying())
{
display.setText("start");
}
oursong.release();
}
else if(letter=="a")
{
oursong = MediaPlayer.create(MainActivity.this, R.raw.a);
oursong.start();
while(oursong.isPlaying())
{
display.setText("start");
}
oursong.release();
}       
display.setText("done");

但出于某种原因,当我点击我的按钮时,没有播放声音。 我也是android和java编程的新手,所以我这样做是对的吗?

因为我真正想要的是程序在点击按钮时继续检查声音是否正在播放(在这种情况下是“我们的”)并且如果声音正在播放我希望程序等待它完成开始紧随其后的另一种声音。 但是现在我的代码没有播放任何声音

1 个答案:

答案 0 :(得分:5)

首先,您需要在发布之前停止媒体播放器(更安全。)

其次,而不是使用while(oursong.isPlaying()) { display.setText("start"); };您必须使用setOnCompletionListener方法注册OnCompletionListener。当播放歌曲时,将调用endCompletion。像这样;

MediaPlayer mp = new MediaPlayer();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
public void onCompletion(MediaPlayer player) {
   player.release();          
}});

并在onComplete内部应重置文本“完成”