Android:如何阻止MediaPlayer播放重叠音频?

时间:2015-10-03 20:18:05

标签: android audio

我正在构建一个暴徒生活音效播放器,我想知道如何阻止MediaPlayer同时播放2个或更多曲目。

这是单击按钮时调用的方法:

    int sequence = 1;
public void thugPlay (View view) {
            // assign a media player to an audio file
    MediaPlayer nothingButThatGthang = MediaPlayer.create(MainActivity.this, R.raw.g_thang);
    MediaPlayer nextEpisode = MediaPlayer.create(MainActivity.this, R.raw.next_episode);
    MediaPlayer fuckThePolice = MediaPlayer.create(MainActivity.this, R.raw.ftp);
    MediaPlayer hipnotize = MediaPlayer.create(MainActivity.this, R.raw.hipnotize);
    MediaPlayer moveBitch = MediaPlayer.create(MainActivity.this, R.raw.move_bitch);
    MediaPlayer ridin = MediaPlayer.create(MainActivity.this, R.raw.ridin);
    MediaPlayer still = MediaPlayer.create(MainActivity.this, R.raw.still);
            // Plays according to sequence's value
    if (sequence == 1) {
        still.stop();
        nothingButThatGthang.start();
        sequence++ ;
    }
    else if (sequence == 2) {
        nothingButThatGthang.stop();
        nextEpisode.start();
        sequence++ ;
    }
    else if (sequence == 3) {
        nextEpisode.stop();
        fuckThePolice.start();
        sequence++ ;
    }
    else if (sequence == 4) {
        fuckThePolice.stop();
        hipnotize.start();
        sequence++ ;
    }
    else if (sequence == 5) {
        hipnotize.stop();
        moveBitch.start();
        sequence++ ;
    }
    else if (sequence == 6) {
        moveBitch.stop();
        ridin.start();
        sequence++ ;
    }
    else {
        ridin.stop();
        still.start();
        sequence = 1 ;
    }
}

正如您所看到的,在播放当前音频文件之前,它应该停止前一个音频文件,但是,它不会发生。

谢谢!

1 个答案:

答案 0 :(得分:2)

创建一个MediaPlayer变量作为类成员:

MediaPlayer mp;

然后在您的点击事件中:

if (mp != null && mp.isPlaying()){
    mp.stop();
}

if (sequence == 1) {
        mp = MediaPlayer.create(MainActivity.this, R.raw.still);
        mp.start();
        sequence++;
    }

你应该在课程中完成If语句。