问题描述
您好,我刚刚创建了一个基本的android应用,可在按钮点击时播放不同的音乐.该应用程序在最初的几秒钟内运行良好,但是当我继续轻按时,有时会停止播放音乐,并且崩溃了……我无法弄清楚问题出在什么地方..请帮助我使其工作..谢谢.这是我的代码:-
Hello there, i have just created a basic android app which plays different musics on button tap..The app just worked fine for the first couple of seconds but when i just keep on tapping and tapping , at some point it stops playing the music and just crashed...I am unable to figure out what the problem is ..Please help me make it work..Thanks.Here is my code :-
public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;
public void PlayMusic(View view)
{
int ID = view.getId();
String NameID = view.getResources().getResourceEntryName(ID);
int sound= getResources().getIdentifier(NameID,"raw","com.example.pickachu.mypatatap");
mediaPlayer = MediaPlayer.create(this,sound);
mediaPlayer.start();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
推荐答案
多次单击后声音无法播放,因为您必须获得IllegalStateException
,因为您不是释放Mediaplayer对象和多次播放时,无法正确管理Mediaplayer生命周期.
您可以使用 setOnCompletionListener(MediaPlayer.OnCompletionListener listener)
在声音完成后释放mediaPlayer
为:
The sound is not playing after multiple taps because you must be getting IllegalStateException
because you are not releasing the Mediaplayer object and Mediaplayer Lifecycles are not managed properly when you tap multiple times.
You can use setOnCompletionListener(MediaPlayer.OnCompletionListener listener)
to release mediaPlayer
after completion of sound as:
mediaPlayer = MediaPlayer.create(this,sound);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.reset();
mp.release();
mediaplayer = null;
}
});
mediaPlayer.start();
这篇关于我的android应用在一段时间后停止在按钮点击时播放声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!