我正在开发一个小小的quizz应用程序,我想播放声音,具体取决于用户是否正确回答了问题。
我在“assets /".
中有很多声音文件我想做的只是播放其中一种声音。 我已经能够播放声音,但不仅一个,声音(正确和不正确)一个接一个地播放。
我怎么能只玩一个? 这是我的来源:
public void audioPlayer(){
//set up MediaPlayer
mp = new MediaPlayer();
try {
String mp3File = "correct.mp3";
AssetManager assetMan = getAssets();
FileInputStream mp3Stream = assetMan.openFd(mp3File).createInputStream();
mp.setDataSource(mp3Stream.getFD());
mp.prepare();
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
答案 0 :(得分:1)
将您的声音文件,即失败和掌声放在原始文件夹中,并使用以下代码:
private AssetFileDescriptor sPlaySoundDescriptor = null;
private AssetFileDescriptor sFailSoundDescriptor = null;
private MediaPlayer mp = null;
public static final int FAIL_SOUND = 1;
public static final int APPLAUSE_SOUND = 2;
public void audioPlayer(int soundType){
//set up MediaPlayer
mp = new MediaPlayer();
AssetFileDescriptor soundFileDescriptor = null;
try {
if (sFailSoundDescriptor == null) {
sFailSoundDescriptor = context.getResources().
openRawResourceFd(R.raw.fail);
}
if (sApplauseSoundDescriptor == null) {
sApplauseSoundDescriptor = context.getResources().
openRawResourceFd(R.raw.applause);
}
switch (soundType) {
case FAIL_SOUND:
soundFileDescriptor = sFailSoundDescriptor;
break;
case APPLAUSE_SOUND:
soundFileDescriptor = sApplauseSoundDescriptor;
break;
}
mp.reset();
mp.setDataSource(soundFileDescriptor.getFileDescriptor(),
soundFileDescriptor.getStartOffset(),
soundFileDescriptor.getDeclaredLength());
mp.prepare();
mp.setOnPreparedListener(new OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer player) {
player.seekTo(0);
player.start();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}