如何在 Android 中播放音效

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10451092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:48:22  来源:igfitidea点击:

How to play a Sound Effect in Android

androidaudio

提问by ThreaT

I'm looking to do a very simple piece of code that plays a sound effect. So far I have this code:

我正在寻找一段非常简单的代码来播放声音效果。到目前为止,我有这个代码:

SoundManager snd;
int combo;

private void soundSetup() {
    // Create an instance of the sound manger
    snd = new SoundManager(getApplicationContext());

    // Set volume rocker mode to media volume
    this.setVolumeControlStream(AudioManager.STREAM_MUSIC);

    // Load the samples from res/raw
    combo = snd.load(R.raw.combo);
}

private void playSound() {
    soundSetup();
    snd.play(combo);
}

However, for some reason when I use the playSound()method, nothing happens. The audio file is in the correct location.

但是,由于某种原因,当我使用该playSound()方法时,没有任何反应。音频文件位于正确的位置。

回答by Sam Clewlow

Is there a specific reason you are using SoundManager? I would use MediaPlayerinstead, here is a link to the Android Docs

您是否有特定的使用原因SoundManager?我会MediaPlayer改用,这里是 Android Docs 的链接

http://developer.android.com/reference/android/media/MediaPlayer.html

http://developer.android.com/reference/android/media/MediaPlayer.html

then it's as simple as

那么就这么简单

    MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.combo);
    mp.start();


Make a directory called "raw/" under the "res/" directory. Drag wav or mp3 files into the raw/ directory. Play them from anywhere as above.

在“res/”目录下创建一个名为“raw/”的目录。将 wav 或 mp3 文件拖到 raw/ 目录中。从上面的任何地方播放它们。

回答by Ivo Robotnik

i have also attempted using the top answer, yet it resulted in NullPointerExceptions from the MediaPlayer when i tried playing a sound many times in a row, so I extended the code a bit.

我也尝试使用最佳答案,但是当我尝试连续多次播放声音时,它导致 MediaPlayer 出现 NullPointerExceptions,因此我稍微扩展了代码。

FXPlayer is my global MediaPlayer.

FXPlayer 是我的全球 MediaPlayer。

public void playSound(int _id)
{
    if(FXPlayer != null)
    {
        FXPlayer.stop();
        FXPlayer.release();
    }
    FXPlayer = MediaPlayer.create(this, _id);
    if(FXPlayer != null)
        FXPlayer.start();
}