0

我正在使用媒体播放器播放声音文件。它在 2.2 和 2.3 上运行良好,但在 ICS 4.0.3 上运行良好,我检查过移动设备未处于静音模式。我的代码是:

private MediaPlayer mediaPlayer;
private void playSound(int soundType) {
    try {
        mediaPlayer = MediaPlayer.create(this, R.raw.beep);
        if (!mediaPlayer.isPlaying()) {
            mediaPlayer.start();
        }
        mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                mediaPlayer.release();
            }
        });
    } catch (IllegalStateException e) {
        e.printStackTrace();
    }
}
4

2 回答 2

0

ICS中的声音是这样播放的:(我从以前的帖子中复制了它,所以如果那里有任何奇怪的东西我道歉)

AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
int mSoundID = mSoundPool.load(this, R.raw.sound1, 1);
float lActualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
float lMaxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float lVolume = lActualVolume / lMaxVolume;
// Is the sound loaded already?
if (mSoundIsLoaded) {
     mSoundPool.play(mSoundID, lVolume, lVolume, 1, 0, 1f);
}

您必须将声音文件放在 assets/raw 目录中。

编辑:我忘了提到 mSoundIsLoaded 参数的来源。我在加载声音时设置它。我在我的 onCreate 方法中执行此操作。加载声音时,我设置了名为 mSoundIsLoaded 的布尔字段。我这样做是为了在播放声音时防止 NullPointerExceptions 声音的加载看起来像这样:

mSoundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
mSoundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
    @Override
    public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
         mSoundIsLoaded = true;
    }
});
mSoundID = mSoundPool.load(this, R.raw.sound1, 1);
于 2012-05-29T11:19:28.670 回答
0

这是我在我的应用程序中使用的代码。它在 ICS 中运行良好

公共无效playWelcomeAudio(){

    Thread t = new Thread()
    {
        @Override
        public void run() {

                AssetFileDescriptor afd = getApplicationContext().getResources().openRawResourceFd(R.raw.welcome); 


                try {
                    if(afd!=null)
                    {
                        UtilLog.d(TAG, "INIT MEDIA PLAYER");
                        welcomeAudio = new MediaPlayer();
                        welcomeAudio.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
                        welcomeAudio.prepare();
                        welcomeAudio.start();
                    }
                } catch (Exception e) {
                    UtilLog.e(TAG, "Audio error", e);
                }

        }
    };
    t.start();
}

您可以删除线程。这不是必需的。

于 2012-05-30T18:51:25.070 回答