Android:在oncreate中循环声音文件

Android:在oncreate中循环声音文件,android,audio,media-player,Android,Audio,Media Player,我想在onCreate()方法中无限循环我的声音mp3文件 我在onCreate方法中的代码如下: mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.sound_7); mMediaPlayer.setVolume(0.2f, 0.2f); Log.e("beep","started1"); mMediaPlayer.setOnCompletionListener(new OnCompletionLi

我想在
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();
但是这段代码只播放我的音频文件一次。请帮忙

提前谢谢。

试试这个

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");
         }
}

请不要在onCreate中执行此操作,而是在onResume中执行此操作。暂停时停止声音@RvdK-谢谢!我在onResume中这样做了,但是当我导航到下一个屏幕并返回到同一屏幕时,如何记住我的声音偏好(开/关)?它总是无限播放,即使我在离开屏幕前停止播放..initializeSoundPool()和playFile()方法之间的区别是什么。对于小文件,哪种方法更好。这里的soundID是什么?