我曾尝试使用媒体播放器,但很容易遇到麻烦。我听从Volodymyr的建议,发现SoundPool更易于管理。
MediaPlayer不喜欢同时播放多个声音,比如当您在按钮上有许多快速选项卡时。我使用以下方法解决了这个问题:
private void playSound(Uri uri) {
try {
mMediaPlayer.reset();
mMediaPlayer.setDataSource(this, uri);
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (Exception e) {
}
在构造函数中,我执行了以下操作:
mMediaPlayer = new MediaPlayer();
mSoundLess = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.less);
mSoundMore = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.more);
当点击时,我将调用 playSound(mSoundLess)
:
相反地,我创建了一个 SoundPool 助手:
package com.mycompany.myapp.util;
import java.util.HashSet;
import java.util.Set;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
public class SoundPoolHelper extends SoundPool {
private Set<Integer> mLoaded;
private Context mContext;
public SoundPoolHelper(int maxStreams, Context context) {
this(maxStreams, AudioManager.STREAM_MUSIC, 0, context);
}
public SoundPoolHelper(int maxStreams, int streamType, int srcQuality, Context context) {
super(maxStreams, streamType, srcQuality);
mContext = context;
mLoaded = new HashSet<Integer>();
setOnLoadCompleteListener(new OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
mLoaded.add(sampleId);
}
});
}
public void play(int soundID) {
AudioManager audioManager = (AudioManager) mContext.getSystemService( Context.AUDIO_SERVICE);
float actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = actualVolume / maxVolume;
if (mLoaded.contains(soundID)) {
play(soundID, volume, volume, 1, 0, 1f);
}
}
}
现在我是这样初始化的:
mSoundPoolHelper = new SoundPoolHelper(1, this);
mSoundLessId = mSoundPoolHelper.load(this, R.raw.less, 1);
mSoundMoreId = mSoundPoolHelper.load(this, R.raw.more, 1);
并播放这样的声音:
private void playSound(int soundId) {
mSoundPoolHelper.play(soundId);
}
不要忘记调用 mSoundPoolHelper.release();
,例如在你的 onDestroy()
中。如果使用 MediaPlayer 也需要类似的操作。