我想无限地在onCreate()
方法中循环我的声音mp3文件。
我在onCreate方法中的代码如下:
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) {
mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.sound_7);
mMediaPlayer.start();
}
});
mMediaPlayer.setLooping(true);
Log.d("beep","started0");
mMediaPlayer.start();
但是此代码只播放我的音频文件一次。请帮忙!!
提前致谢。
答案 0 :(得分:0)
试试这个
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");
}
}