【问题标题】:android : when using MediaPlayer to play background music, sound effects are stopped prematurelyandroid : 使用 MediaPlayer 播放背景音乐时,音效过早停止
【发布时间】:2012-08-24 08:51:34
【问题描述】:

我正在尝试在我的应用上播放背景音乐,并在你杀死敌人时偶尔播放音效之类的东西。

所有的音效都正常工作,但后来我开始使用 MusicManager 类(类似于本教程:http://www.rbgrn.net/content/307-light-racer-20-days-61-64-completion)来尝试播放背景音乐,它可以正常工作,但音效在半秒左右后就被切断了。

我正在播放音效:

 MediaPlayer mp = MediaPlayer.create(context, R.raw.fire); 
 mp.start();

【问题讨论】:

    标签: android background effects


    【解决方案1】:

    改用声音池。 SoundPool 可以同时以不同的音量、速度和循环播放多个流。 MediaPLayer 并不是真的要处理游戏音频。

    我在市场上发布了 2 款游戏,都使用 SoundPool 并且没有问题。

    这两个函数是从我的游戏中取出来的。

       public static void playSound(int index, float speed) 
    {       
             float streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC); 
             streamVolume = streamVolume / mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
             mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, 0, speed); 
    }
    public static void playLoop(int index, float speed) 
    {       
             float streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC); 
             streamVolume = streamVolume / mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
             streamVolume = streamVolume / 3f;
             mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, -1, speed); 
    }
    

    就是这么简单。仔细看一下,我只使用我的 playLoop() 播放背景音乐,所以我降低了它的音量,但是你可以很容易地修改代码来手动设置每次播放的音量。

    还有

         mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, -1, speed);
    

    第一个参数 mSoundPoolMap.get(index) 只是一个包含我所有声音的容器。我为每个声音分配一个最终编号,例如

        final static int SOUND_FIRE = 0, SOUND_DEATH = 1, SOUND_OUCH = 2;
    

    我将这些声音加载到这些位置并从中播放它们。 (请记住,您不想每次运行时都加载所有声音,只需加载一次。)接下来的 2 个参数是左/右音量、优先级,然后 -1 设置为循环。

        mSoundPool = new SoundPool(8, AudioManager.STREAM_MUSIC, 0);
    

    这会将我的声音池设置为 8 个流。另一个是源类型,然后是质量。

    玩得开心!

    【讨论】:

    • SoundPool 用于音效和背景音乐?谢谢! =]
    • 没问题,我扔了一些代码给你看:)如果答案好,别忘了接受:)
    • 我正在尝试这个解决方案,但现在我无法播放任何声音。 =[也许我弄错了AudioManager?基本上我只是在做:AudioManager mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    • 我刚刚找到了一个其他人创建的简单框架供您查看。 (我只是不想放弃我所有的东西,希望你能理解)。 sgap.springnote.com/pages/5294563.xhtml
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多