Android: 播放声音的有效方式

Android: Efficent Way of playing Sounds

这是我的代码,给你看再解释会更容易:

public class Sound {
    public MediaPlayer audio;

    public Sound(Context context, int id) {
        audio = MediaPlayer.create(context.getApplicationContext(), id);
    }
}

public class ClassA {
    Sound sound = new Sound(getContext(), R.raw.audio);

    public void method() {
        //plays only once here, so its not looping, which is good
        sound.audio.start();
    }
}

所以我想在这里做的是有一个定义声音的 class,然后允许我播放它,但是当我在我的 phone 上加载我的应用程序时,它崩溃了。

我今天才开始接触声音,所以不太了解。我不知道为什么这不起作用,我计划今天发布我的第一个应用程序。
非常感谢您的帮助!

忘了说,我这样做的原因是我的游戏声音不会因为创建许多 MediaPlayer 而崩溃。

对于较短的声音样本,最好使用 android.media.SoundPool.

import android.content.Context;
import android.media.*;

您 Activity

中的任意位置
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
SoundPool soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
int soundId = soundPool.load(theContext, R.raw.audio, 1);
int streamVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
int streamId = soundPool.play(soundId, streamVolume, streamVolume, 1, 0, 1f);