我有一些代码设置/raw/
,使用该android.media.MediaPlayer
对象一个接一个地在我的文件夹中播放 3 个声音文件。每次调用 MediaPlayer 播放时,都会随机选择 3 个声音中的两个。
但是,我意识到这确实不是最好的方法,因为声音片段太短了。我已经看了一点android.media.SoundPool
。但是我不确定如何合并SoundPool
而不是使用MediaPlayer
. 这就是我目前所拥有的。
任何关于我如何基本上从使用 MediaPlayer 更改为 SoundPool 的指针将不胜感激。
mpButtonOne = MediaPlayer.create(camera_page.this, R.raw.default);
if (mpButtonOne==null){
//display a Toast message here
return;
}
mpButtonOne.start();
mpButtonOne.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
int audio = mfile[rnd.nextInt(SOUND_CLIPS)];
audioReplayPrimary = audio;
mpButtonOne.reset();
mpButtonOne = MediaPlayer.create(camera_page.this, audio);
if (mpButtonOne==null){
//display a Toast message here
return;
}
mpButtonOne.start();
mpButtonOne.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
int audio2 = mfile2[rnd.nextInt(SOUND_CLIPS2)];
audioReplaySecondary = audio2;
mpButtonOne.reset();
mpButtonOne = MediaPlayer.create(camera_page.this, audio2);
if (mpButtonOne==null){
//display a Toast message here
return;
}
mpButtonOne.start();
mpButtonOne.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mpButtonOne.release();
}
更新
private static SoundPool mSoundPool;
private static AudioManager mAudioManager;
private final int SOUND_CLIPS3 = 5;
private int mfile3[] = new int[SOUND_CLIPS3];
private Random rnd = new Random();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sptest);
mfile3[0] = R.raw.one;
mfile3[1] = R.raw.two;
mfile3[2] = R.raw.three;
mfile3[3] = R.raw.four;
mfile3[4] = R.raw.five;
mSoundPool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0);
mAudioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
Button spTest = (Button) findViewById(R.id.buttonSp);
spTest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int audioPre = mfile3[rnd.nextInt(SOUND_CLIPS3)];
int sound1 = mSoundPool.load(sptestclass.this, audioPre, 1);
mSoundPool.play(sound1, 1f, 1f, 1, 0, 1f);
}
});