好吧,我有一个带声音的ListView。当我点击其中一个时,它开始播放那首歌,但是当我点击其他一个/它时,它仍在播放。我想要做的是当我按下另一个时停止那个声音。我谷歌它,在这里找到完全相同的问题解决方案,但它不适合我。我得到错误,其中说:“MediaPlayer类型中的方法setDataSource(String)不适用于参数(int)”。我只是不知道如何获得具体位置,点击了哪个项目行。这就是我现在在onListItemClick()方法中所拥有的:
@Override
public void onListItemClick(ListView parent, View v, int position, long id) {
Minions s = (Minions) mSounds.get(position);
MediaPlayer mPlayer;
final boolean isPlaying = false;
if(!isPlaying){
mPlayer = new MediaPlayer();
mPlayer.setDataSource(s.getSoundResourceId());
mPlayer.prepare();
mPlayer.start();
isPlaying = true;
}else{
isPlaying = false;
mPlayer.stop();
mPlayer.reset();
mPlayer.setDataSource(s.getSoundResourceId());
mPlayer.prepare();
mPlayer.start();
isPlaying = true;
}
mPlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mPlayer) {
mPlayer.release();
isPlaying = false;
}
});
}
答案 0 :(得分:2)
在我的情况下,我会这样做:
代替:
mediaPlayer= new MediaPlayer();
mediaPlayer.setDataSource(s.getSoundResourceId());
使用:
mediaPlayer=MediaPlayer.create(context,R.raw.blabla);
这里您不需要prepare
private MediaPlayer mPlayer;
....
@Override
public void onListItemClick(ListView parent, View v, int position, long id) {
final boolean isPlaying = false;
if(!isPlaying){
mediaPlayer=MediaPlayer.create(context,R.raw.blabla);
mPlayer.start();
isPlaying = true;
}else{
isPlaying = false;
mPlayer.stop();
mPlayer.reset();
mediaPlayer=MediaPlayer.create(context,R.raw.blabla);
mPlayer.start();
isPlaying = true;
}
mPlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mPlayer) {
mPlayer.release();
isPlaying = false;
}
});
}
答案 1 :(得分:1)
尝试setDataSource(""+s.getSoundResourceId());
而不是setDataSource(s.getSoundResourceId());
PS。也会初始化mPlayer
喜欢MediaPlayer mPlayer=new MediaPlayer();
而不是MediaPlayer mPlayer;
并从if条件中删除此mPlayer = new MediaPlayer();
!