尝试这个
void playMp3()
{
mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.sound_7);
mMediaPlayer.setVolume(0.2f, 0.2f);
Log.e("beep","started1");
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer arg0) {
playMp3();
}
});
Log.d("beep","started0");
mMediaPlayer.start();
}
如果你的声音文件很小,那么SoundPool
而不是MediaPlayer
private void initializeSoundPool(){
mSoundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
mSoundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
public void onLoadComplete(SoundPool soundPool, int sampleId,
int status) {
loaded = true;
playFile();
initializeSoundPool();
}
});
soundID = mSoundPool.load(this, R.raw.glassbreak, 1);
}
调用这个方法
private void playFile(){
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
float actualVolume = (float) audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = actualVolume / maxVolume;
if (loaded) {
mSoundPool.play(soundID, volume, volume, 1, 0, 1f);
Log.e("Test", "Played sound");
}
}