媒体播放器声音停止()不起作用



我在一个活动的菜单中有这两个选项

选项一开始播放音乐,选项二应该停止它,但是它没有。

    @Override
public boolean onOptionsItemSelected(MenuItem item) {
     MediaPlayer mpSoundTrack = MediaPlayer.create(this, R.raw.app_score);
    switch (item.getItemId()) {
        case R.id.icon:     Toast.makeText(this, "Music On!", Toast.LENGTH_LONG).show();
        mpSoundTrack.start();
                            break;
        case R.id.icontext: Toast.makeText(this, "Music Off!", Toast.LENGTH_LONG).show();
        mpSoundTrack.stop(); 
                            break;
    }
    return true;
     }

每次创建一个新的mediaPlayer时,都要停止一个新的,而不是旧的。你应该保留对它的引用:

private MediaPlayer mpSoundTrack = null;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.icon:     
            Toast.makeText(this, "Music On!", Toast.LENGTH_LONG).show();
            mpSoundTrack = MediaPlayer.create(this, R.raw.app_score);
            mpSoundTrack.start();
            break;
        case R.id.icontext: 
            Toast.makeText(this, "Music Off!", Toast.LENGTH_LONG).show();
            if(mpSoundTrack != null)
                mpSoundTrack.stop(); 
            break;
    }
    return true;
}

最新更新