几乎是标题。使用ListView,在单击项目时,将合适的原始文件ID传递给playound方法。 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的main方法中将playing变量初始化为零(onItemClick是其中的一部分)。
答案 0 :(得分:1)
每次调用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.
}