差不多是标题。使用 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;
}
}
播放变量在 Activity 的主方法中初始化为零(onItemClick 是其中的一部分(。
每次调用方法时都会创建一个MediaPlayer
实例playSound()
这是不正确的,这基本上是问题所在,请执行以下操作:
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()
然后如果它正在播放,只需停止stop()
:
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.
}