我有一个按钮,当按下该按钮时,它会播放从Firebase存储中获取的mp3文件,问题是如果我按两次按钮,音频会重叠。再次按下按钮时如何使音频暂停?很抱歉,如果以前回答过这个问题,但我是新来的,如果不是我个人的情况,我很难理解。
button2=findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
MediaPlayer player = new MediaPlayer();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource("https://firebasestorage.googleapis.com/v0/b/yovoicest2.appspot.com/o/songs%2FDeath.mp3?alt=media&token=925d52c3-e5a7-4b2c-a598-e83a97730a24");
player.prepare();
player.start();
} catch (Exception e) {
// TODO: handle exception
}
}
});```
答案 0 :(得分:1)
将Media Player定义为Member变量并检查。
MediaPlayer player = new MediaPlayer();
button2=findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(player != null && player.isPlaying()) {
// Handle the playing like changing the button Text/Image
player.stop();
} else {
// Handle the stop like changing the button Text/Image
//Do your thing. Initialize it again with whatever file you want.
}
}
});