/** * 根据path路径播放背景音乐 * * @param path * :assets中的音频路径 * @param isLoop * :是否循环播放 */ publicvoidplayBackgroundMusic(int path, boolean isLoop){ if (mCurrentPath == 0) { // 这是第一次播放背景音乐--- it is the first time to play background music // 或者是执行end()方法后,重新被叫---or end() was called mBackgroundMediaPlayer = createMediaPlayerFromPath(path); mCurrentPath = path; } else { if (mCurrentPath != path) { // 播放一个新的背景音乐--- play new background music // 释放旧的资源并生成一个新的----release old resource and create a new one if (mBackgroundMediaPlayer != null) { mBackgroundMediaPlayer.release(); } mBackgroundMediaPlayer = createMediaPlayerFromPath(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 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"); } } }
/** * 停止播放背景音乐 */ publicvoidstopBackgroundMusic(){ if (mBackgroundMediaPlayer != null) { mBackgroundMediaPlayer.stop(); // should set the state, if not , the following sequence will be // error // play -> pause -> stop -> resume this.mIsPaused = false; } }