听起来不适合ICS

时间:2012-05-29 11:03:41

标签: android android-layout android-widget

我正在使用媒体播放器播放声音文件。它在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();
    }
}

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

这是我在我的应用程序中使用的代码..它在ICS中工作正常

public void 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();
}

您可以删除该帖子。这不是必需品。