1

我想在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();

但是这段代码只播放我的音频文件一次。请帮忙 !!

提前致谢。

4

1 回答 1

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");
         }
}
于 2013-03-14T09:54:53.607 回答