gpt4 book ai didi

Android MediaPlayer 停止()不起作用

转载 作者:行者123 更新时间:2023-11-29 23:41:40 24 4
gpt4 key购买 nike

差不多是标题。使用 ListView,在单击一个项目时,合适的原始文件 ID 将传递给 playsound 方法。 start() 工作正常,但 stop() 不执行任何操作。

public class AmbienceActivity extends AppCompatActivity {

private MediaPlayer sound;

ListView list;
String[] web = {
"Breeze",
"Birds Chirping",
"Rain on Window",
"Cafe"
};
Integer[] imageId = {
R.mipmap.ic_launcher_round,
R.mipmap.ic_launcher_round,
R.mipmap.ic_launcher_round,
R.mipmap.ic_launcher_round
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ambience);

SoundsList adapter = new SoundsList(AmbienceActivity.this, web, imageId);
list = (ListView) findViewById(R.id.soundslist);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if(position==0)
playSound(R.raw.breeze);
else if(position==1)
playSound(R.raw.birds_chatter);
else if(position==2)
playSound(R.raw.rain_on_window);
else if(position==3)
playSound(R.raw.cafe_chatter);
}
});
}

protected void playSound ( int x){
int soundPlaying = 0;
sound = MediaPlayer.create(this,x);
if (x != soundPlaying && sound != null) { //Play a new sound
sound.release();
sound = null;
sound = MediaPlayer.create(this, x);
} else { //Play sound
sound = MediaPlayer.create(this, x);
}

if (sound != null && !sound.isPlaying()) {
sound.start();
} else if (sound != null && sound.isPlaying()) {
sound.stop();
}

soundPlaying = x;
}
}

playing 变量在 Activity 的 main 方法中被初始化为零(onItemClick 是其中的一部分)。

最佳答案

每次调用 playSound() 方法时,您都在创建一个 MediaPlayer 实例,这是不正确的,这基本上就是问题所在,请执行以下操作:

private MediaPlayer sound;
protected void playSound (int x){
//MediaPlayer sound = MediaPlayer.create(this,x);
if(sound != null){
sound.release();
sound = null;
sound = MediaPlayer.create(this,x);
}
...
...
}

现在,你不需要一个变量来检测 MediaPlayer 是否正在播放,使用方法 isPlaying() 然后如果它正在播放就停止 停止():

private MediaPlayer sound;

protected void playSound (int x){
int soundPlaying = 0;
//MediaPlayer sound = MediaPlayer.create(this,x);

if(x != soundPlaying && sound != null){ //Play a new sound
sound.release();
sound = null;
sound = MediaPlayer.create(this,x);
}else{ //Play sound
sound = MediaPlayer.create(this,x);
}

if(sound != null && !sound.isPlaying()) {
sound.start();
//playing = 1;

} else if(sound != null && sound.isPlaying()){
sound.stop();
// playing = 0;
}

soundPlaying = x; //current id of sound.
}

关于Android MediaPlayer 停止()不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51794381/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com