我怎样才能让Android媒体播放器播放的声音?媒体播放器、声音、Android

2023-09-05 05:00:35 作者:不归

我不知道为什么它不工作,没有错误记录在logcat中,但我不能听到声音。

I don't know why it doesn't works, there is no error logged in logcat, but I cannot hear a sound.

public static void DeclararSonido(int numero, Context contexto){
    switch(numero){
    case 0:
        mp = MediaPlayer.create(contexto, R.raw.alan);
        break;          
    }
}

public static void TocarPiedra( int posicion, Context contexto){
    DeclararSonido(posicion, contexto);


    mp.start();
    mp.stop();
    mp.release();
}
public static void TocarSirena(Context contexto){
    MediaPlayer mp2= MediaPlayer.create(contexto, R.raw.doh);


    mp2.start();
    mp2.stop();
    mp2.release();

}

如果我删除 mp2.stop(); mp2.release(); mp.stop(); mp.release(); 应用程序播放声音,但该文件没有被释放...

If I erase mp2.stop(); and mp2.release(); AND mp.stop(); and mp.release(); the app plays the sound, but the file is not released...

推荐答案

您显然不希望开始,然后停在离..

You obviously do not want to Start and then Stop right away..

现在的问题是,你在执行后对方这些正确的:

The problem is that you are executing these right after each other:

mp.start();      // starts playback
mp.stop();       // .. then stops immediately ..
mp.release();

您应该开始,然后当声音进行播放,发布。您可以使用完成事件挂钩一个侦听和释放有:

You should start, and then when the sound is done playing, release. You can use the Completion event to hook up a listener and release there:

mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
    public void onCompletion(MediaPlayer player) {
       player.release();          
    }
})