请帮助我,我想用单个按钮使用yate fisher shuffle算法随机播放原始文件夹android studio的声音。 我使用这段代码:
public void playSound() {
MediaPlayer mp;
int[] rawSoal = {R.raw.al, R.raw.fear, R.raw.love};
shuffleArray(rawSoal);
for (int i = 0; i < rawSoal.length; i++) ;
try {
Random random = new Random();
mp = MediaPlayer.create(this, rawSoal[random.nextInt(rawSoal.length)]);
mp.start();
mp.release();
}catch(Exception e){
Log.e("ERROR", "Media Player", e);
mp = null;
}
}
实施Fisher-Yates shuffle
static void shuffleArray(int[] ar) {
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
通话按钮:
plybtn.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
playSound();
mp.release();
}
});
答案 0 :(得分:0)
试试这个:
public void playSound() {
MediaPlayer mp;
int[] rawSoal = {R.raw.al, R.raw.fear, R.raw.love};
shuffleArray(rawSoal);
try {
int idx = new Random().nextInt(rawSoal.length);
mp = MediaPlayer.create(this, rawSoal[idx]);
mp.start();
mp.release();
}catch(Exception e){
Log.e("ERROR", "Media Player", e);
mp = null;
}
}
static void shuffleArray(int[] arr)
{
Random rnd = new Random();
for (int i = arr.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Swap
int a = arr[index];
arr[index] = arr[i];
arr[i] = a;
}
}
答案 1 :(得分:0)
我认为因为你刚刚在start()之后发布了MediaPlayer。所以音频没有播放。音频完成时释放MediaPlayer。