Realization of Background Music Playing Function by android

  • 2021-09-05 00:59:31
  • OfStack

Refer to the one written by others on the Internet, and put it in a new thread to play music when using it again. Later, it was found that every time you enter Activity, you will repeat the sound of playing music. In order to avoid turning on the playback function repeatedly, I added singleton mode on the basis of the original code. In this way, repeated playback is avoided.


package com.liu.zhen.utils; 
 
import android.content.Context; 
import android.content.res.AssetFileDescriptor; 
import android.media.MediaPlayer; 
import android.util.Log; 
 
/** 
 * 
 * This class is used for controlling background music 
 * 
 */ 
public class BackgroundMusic { 
  private static BackgroundMusic backgroundMusic = null; 
  private static final String TAG = "Bg_Music"; 
  private float mLeftVolume; 
  private float mRightVolume; 
  private Context mContext; 
  private MediaPlayer mBackgroundMediaPlayer; 
  private boolean mIsPaused; 
  private String mCurrentPath; 
 
  private BackgroundMusic(Context context) { 
    this.mContext = context; 
    initData(); 
  } 
 
  public static BackgroundMusic getInstance(Context context) { 
    if (backgroundMusic == null) { 
      backgroundMusic = new BackgroundMusic(context); 
    } 
    return backgroundMusic; 
  } 
 
  //  Initialization 1 Some data  
  private void initData() { 
    mLeftVolume = 0.5f; 
    mRightVolume = 0.5f; 
    mBackgroundMediaPlayer = null; 
    mIsPaused = false; 
    mCurrentPath = null; 
  } 
 
  /** 
   *  According to path Path to play background music  
   * 
   * @param path 
   *      :assets Audio path in  
   * @param isLoop 
   *      : Loop or not  
   */ 
  public void playBackgroundMusic(String path, boolean isLoop) { 
    if (mCurrentPath == null) { 
      //  This is the first 1 Play background music once --- it is the first time to play background music 
      //  Or execute end() Method, call again ---or end() was called 
      mBackgroundMediaPlayer = createMediaplayerFromAssets(path); 
      mCurrentPath = path; 
    } else { 
      if (!mCurrentPath.equals(path)) { 
        //  Play 1 A new background music --- play new background music 
        //  Release old resources and generate 1 A new one ----release old resource and create a new one 
        if (mBackgroundMediaPlayer != null) { 
          mBackgroundMediaPlayer.release(); 
        } 
        mBackgroundMediaPlayer = createMediaplayerFromAssets(path); 
        //  Record this path ---record the path 
        mCurrentPath = path; 
      } 
    } 
 
    if (mBackgroundMediaPlayer == null) { 
      Log.e(TAG, "playBackgroundMusic: background media player is null"); 
    } else { 
      //  If the music is playing or is nearly interrupted, stop it ---if the music is playing or paused, stop it 
      mBackgroundMediaPlayer.stop(); 
      mBackgroundMediaPlayer.setLooping(isLoop); 
      try { 
        mBackgroundMediaPlayer.prepare(); 
        mBackgroundMediaPlayer.seekTo(0); 
        mBackgroundMediaPlayer.start(); 
        this.mIsPaused = false; 
      } catch (Exception e) { 
        Log.e(TAG, "playBackgroundMusic: error state"); 
      } 
    } 
  } 
 
  /** 
   *  Stop playing background music  
   */ 
  public void stopBackgroundMusic() { 
    if (mBackgroundMediaPlayer != null) { 
      mBackgroundMediaPlayer.stop(); 
      // should set the state, if not , the following sequence will be 
      // error 
      // play -> pause -> stop -> resume 
      this.mIsPaused = false; 
    } 
  } 
 
  /** 
   *  Pause playing background music  
   */ 
  public void pauseBackgroundMusic() { 
    if (mBackgroundMediaPlayer != null 
        && mBackgroundMediaPlayer.isPlaying()) { 
      mBackgroundMediaPlayer.pause(); 
      this.mIsPaused = true; 
    } 
  } 
 
  /** 
   *  Continue playing background music  
   */ 
  public void resumeBackgroundMusic() { 
    if (mBackgroundMediaPlayer != null && this.mIsPaused) { 
      mBackgroundMediaPlayer.start(); 
      this.mIsPaused = false; 
    } 
  } 
 
  /** 
   *  Replay background music  
   */ 
  public void rewindBackgroundMusic() { 
    if (mBackgroundMediaPlayer != null) { 
      mBackgroundMediaPlayer.stop(); 
      try { 
        mBackgroundMediaPlayer.prepare(); 
        mBackgroundMediaPlayer.seekTo(0); 
        mBackgroundMediaPlayer.start(); 
        this.mIsPaused = false; 
      } catch (Exception e) { 
        Log.e(TAG, "rewindBackgroundMusic: error state"); 
      } 
    } 
  } 
 
  /** 
   *  Judge whether background music is playing or not  
   * 
   * @return Returned boolean Value represents whether it is playing  
   */ 
  public boolean isBackgroundMusicPlaying() { 
    boolean ret = false; 
    if (mBackgroundMediaPlayer == null) { 
      ret = false; 
    } else { 
      ret = mBackgroundMediaPlayer.isPlaying(); 
    } 
    return ret; 
  } 
 
  /** 
   *  End background music and release resources  
   */ 
  public void end() { 
    if (mBackgroundMediaPlayer != null) { 
      mBackgroundMediaPlayer.release(); 
    } 
    //  Re-initialize data  
    initData(); 
  } 
 
  /** 
   *  Get the "volume" of background music  
   * 
   * @return 
   */ 
  public float getBackgroundVolume() { 
    if (this.mBackgroundMediaPlayer != null) { 
      return (this.mLeftVolume + this.mRightVolume) / 2; 
    } else { 
      return 0.0f; 
    } 
  } 
 
  /** 
   *  Set the volume of background music  
   * 
   * @param volume 
   *       Set the volume of playback, float Type  
   */ 
  public void setBackgroundVolume(float volume) { 
    this.mLeftVolume = this.mRightVolume = volume; 
    if (this.mBackgroundMediaPlayer != null) { 
      this.mBackgroundMediaPlayer.setVolume(this.mLeftVolume, 
          this.mRightVolume); 
    } 
  } 
 
  /** 
   * create mediaplayer for music 
   * 
   * @param path 
   *      the path relative to assets 
   * @return 
   */ 
  private MediaPlayer createMediaplayerFromAssets(String path) { 
    MediaPlayer mediaPlayer = null; 
    try { 
      AssetFileDescriptor assetFileDescritor = mContext.getAssets() 
          .openFd(path); 
      mediaPlayer = new MediaPlayer(); 
      mediaPlayer.setDataSource(assetFileDescritor.getFileDescriptor(), 
          assetFileDescritor.getStartOffset(), 
          assetFileDescritor.getLength()); 
      mediaPlayer.prepare(); 
      mediaPlayer.setVolume(mLeftVolume, mRightVolume); 
    } catch (Exception e) { 
      mediaPlayer = null; 
      Log.e(TAG, "error: " + e.getMessage(), e); 
    } 
    return mediaPlayer; 
  } 
} 

Related articles: