SoFunction
Updated on 2025-04-10

Android implements background music playback function

I have referenced what someone wrote on the Internet. When I use it, I put it in a newly opened thread to play music. Later, I found that every time I enter the Activity, I will start a music playback sound repeatedly. In order to avoid repeatedly turning on the playback function, I added singleton mode to the original code. This avoids repeated playback.

package ; 
 
import ; 
import ; 
import ; 
import ; 
 
/** 
 * 
 * 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) { 
     = context; 
    initData(); 
  } 
 
  public static BackgroundMusic getInstance(Context context) { 
    if (backgroundMusic == null) { 
      backgroundMusic = new BackgroundMusic(context); 
    } 
    return backgroundMusic; 
  } 
 
  // Initialize some data  private void initData() { 
    mLeftVolume = 0.5f; 
    mRightVolume = 0.5f; 
    mBackgroundMediaPlayer = null; 
    mIsPaused = false; 
    mCurrentPath = null; 
  } 
 
  /**
    * Play background music according to path path
    *
    * @param path
    *: Audio path in assets
    * @param isLoop
    *: Whether to play it loop
    */ 
  public void playBackgroundMusic(String path, boolean isLoop) { 
    if (mCurrentPath == null) { 
      // This is the first time to play background music --- it is the first time to play background music      // Or after executing the end() method, it is called again --- or end() was called      mBackgroundMediaPlayer = createMediaplayerFromAssets(path); 
      mCurrentPath = path; 
    } else { 
      if (!(path)) { 
        // Play a new background music --- play new background music        // Release old resource and create a new one        if (mBackgroundMediaPlayer != null) { 
          (); 
        } 
        mBackgroundMediaPlayer = createMediaplayerFromAssets(path); 
        // Record this path ---record the path        mCurrentPath = path; 
      } 
    } 
 
    if (mBackgroundMediaPlayer == null) { 
      (TAG, "playBackgroundMusic: background media player is null"); 
    } else { 
      // If the music is playing or is almost interrupted, stop it ----if the music is playing or paused, stop it      (); 
      (isLoop); 
      try { 
        (); 
        (0); 
        (); 
         = false; 
      } catch (Exception e) { 
        (TAG, "playBackgroundMusic: error state"); 
      } 
    } 
  } 
 
  /**
    * Stop playing background music
    */ 
  public void stopBackgroundMusic() { 
    if (mBackgroundMediaPlayer != null) { 
      (); 
      // should set the state, if not , the following sequence will be 
      // error 
      // play -> pause -> stop -> resume 
       = false; 
    } 
  } 
 
  /**
    * Pause background music playback
    */ 
  public void pauseBackgroundMusic() { 
    if (mBackgroundMediaPlayer != null 
        && ()) { 
      (); 
       = true; 
    } 
  } 
 
  /**
    * Continue playing background music
    */ 
  public void resumeBackgroundMusic() { 
    if (mBackgroundMediaPlayer != null && ) { 
      (); 
       = false; 
    } 
  } 
 
  /**
    * Replay background music
    */ 
  public void rewindBackgroundMusic() { 
    if (mBackgroundMediaPlayer != null) { 
      (); 
      try { 
        (); 
        (0); 
        (); 
         = false; 
      } catch (Exception e) { 
        (TAG, "rewindBackgroundMusic: error state"); 
      } 
    } 
  } 
 
  /**
    * Determine whether the background music is playing
    *
    * @return: The returned boolean value represents whether it is playing
    */ 
  public boolean isBackgroundMusicPlaying() { 
    boolean ret = false; 
    if (mBackgroundMediaPlayer == null) { 
      ret = false; 
    } else { 
      ret = (); 
    } 
    return ret; 
  } 
 
  /**
    * End background music and free up resources
    */ 
  public void end() { 
    if (mBackgroundMediaPlayer != null) { 
      (); 
    } 
    // Re-initialize data    initData(); 
  } 
 
  /**
    * Get the "volume" of background music
    *
    * @return
    */ 
  public float getBackgroundVolume() { 
    if ( != null) { 
      return ( + ) / 2; 
    } else { 
      return 0.0f; 
    } 
  } 
 
  /**
    * Set the volume of background music
    *
    * @param volume
    *: Set the playback volume, float type
    */ 
  public void setBackgroundVolume(float volume) { 
     =  = volume; 
    if ( != null) { 
      (, 
          ); 
    } 
  } 
 
  /** 
   * create mediaplayer for music 
   * 
   * @param path 
   *      the path relative to assets 
   * @return 
   */ 
  private MediaPlayer createMediaplayerFromAssets(String path) { 
    MediaPlayer mediaPlayer = null; 
    try { 
      AssetFileDescriptor assetFileDescritor = () 
          .openFd(path); 
      mediaPlayer = new MediaPlayer(); 
      ((), 
          (), 
          ()); 
      (); 
      (mLeftVolume, mRightVolume); 
    } catch (Exception e) { 
      mediaPlayer = null; 
      (TAG, "error: " + (), e); 
    } 
    return mediaPlayer; 
  } 
} 

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.