gpt4 book ai didi

android - 使单个MediaPlayer在android studio中播放多个声音的代码

转载 作者:行者123 更新时间:2023-12-03 01:27:43 27 4
gpt4 key购买 nike

作为一名新手程序员,尝试编写片段中单击按钮时会播放声音的应用程序;成功做到了这一点,但我想添加更多小声音来逐个播放。如何在“R.raw.sound1”之后添加这些声音(sound2,sound3,sound4等)?请指导。

 buttonPlayAudioVar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {


if(mp != null) {
if(mp.isPlaying()){
mp.stop();
mp.release();
}
}

mp = MediaPlayer.create(getActivity().getApplicationContext(), R.raw.sound1);
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayer) {
mp.release();
mp = null;

}
});
}
});

最佳答案

   //you can add all the songs in a array

ArrayList<String> songsArray = new ArrayList<>();
int position = 0;

buttonPlayAudioVar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mediaPlayer(songsArray, position);
}
});

private void mediaPlayer(ArrayList<String> songsArray) {
if (mp != null) {
if (mp.isPlaying()) {
mp.stop();
mp.release();
}
}

if (position > songsArray.size() - 1) {
return;
}

try {
mp.setDataSource(songsArray.get(position));

position++;
mp.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}

mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});

mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayer) {
mp.release();
mp = null;
mediaPlayer(songsArray, position);
}
});
}

关于android - 使单个MediaPlayer在android studio中播放多个声音的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59360895/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com