您的位置:首页 > 其它

*********背景音乐*******

2015-06-30 11:20 183 查看
*********背景音乐*******

1.通过android,实现背景音乐效果

(1)项目简图如图所示:



(2)多线程实现后台播放背景音乐的主要代码如下:

package com.example.service;

import android.app.Service;

import android.content.Intent;

import android.media.MediaPlayer;

import android.os.Binder;

import android.os.IBinder;

public class AudioService extends Service implements

MediaPlayer.OnCompletionListener {

// 实例化MediaPlayer对象

MediaPlayer player;

private final IBinder binder = new AudioBinder();

@Override

public IBinder onBind(Intent intent) {

return binder;

}

public void onCreate() {

super.onCreate();

// 从raw文件夹中获取一个应用自带的mp3文件

player = MediaPlayer.create(this, R.raw.qq);

player.setOnCompletionListener(this);

player.setLooping(true);

}

@Override

public int onStartCommand(Intent intent, int flags, int startId) {

super.onStartCommand(intent, flags, startId);

if (!player.isPlaying()) {

new MusicPlayThread().start();

}

else player.isPlaying();

return START_STICKY;

}

/**

* 当Audio播放完的时候触发该动作

*/

public void onCompletion(MediaPlayer mp) {

stopSelf();// 结束了,则结束Service

}

public void onDestroy() {

super.onDestroy();

if (player.isPlaying()) {

player.stop();

}

player.release();

}

// 为了和Activity交互,我们需要定义一个Binder对象

public class AudioBinder extends Binder {

// 返回Service对象

public AudioService getService() {

return AudioService.this;

}

}

private class MusicPlayThread extends Thread {

public void run() {

if (!player.isPlaying()) {

player.start();

}

}

}

}

实例AndroidManifest.xml文件配置Service

<application
android:allowBackup="true"


android:icon="@drawable/ic_launcher"


android:label="@string/app_name"


android:theme="@style/AppTheme" >


<activity


android:name="com.example.musicproject.MainActivity"


android:label="@string/app_name" >


<intent-filter>


<action
android:name="android.intent.action.MAIN" />


<category
android:name="android.intent.category.LAUNCHER" />


</intent-filter>


</activity>


<service
android:name=".MusicService">


</service>


</application>


为了避免重复开启播放功能我在原来代码的基础上增加了单例模式

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

// 初始化一些数据
private void initData() {
mLeftVolume = 0.5f;
mRightVolume = 0.5f;
mBackgroundMediaPlayer = null;
mIsPaused = false;
mCurrentPath = null;
}

/**
* 根据path路径播放背景音乐
*
* @param path
* :assets中的音频路径
* @param isLoop
* :是否循环播放
*/
public void playBackgroundMusic(String path, boolean isLoop) {
if (mCurrentPath == null) {
// 这是第一次播放背景音乐--- it is the first time to play background music
// 或者是执行end()方法后,重新被叫---or end() was called
mBackgroundMediaPlayer = createMediaplayerFromAssets(path);
mCurrentPath = path;
} else {
if (!mCurrentPath.equals(path)) {
// 播放一个新的背景音乐--- play new background music
// 释放旧的资源并生成一个新的----release old resource and create a new one
if (mBackgroundMediaPlayer != null) {
mBackgroundMediaPlayer.release();
}
mBackgroundMediaPlayer = createMediaplayerFromAssets(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");
}
}
}

/**
* 停止播放背景音乐
*/
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;
}
}

/**
* 暂停播放背景音乐
*/
public void pauseBackgroundMusic() {
if (mBackgroundMediaPlayer != null
&& mBackgroundMediaPlayer.isPlaying()) {
mBackgroundMediaPlayer.pause();
this.mIsPaused = true;
}
}

/**
* 继续播放背景音乐
*/
public void resumeBackgroundMusic() {
if (mBackgroundMediaPlayer != null && this.mIsPaused) {
mBackgroundMediaPlayer.start();
this.mIsPaused = false;
}
}

/**
* 重新播放背景音乐
*/
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");
}
}
}

/**
* 判断背景音乐是否正在播放
*
* @return:返回的boolean值代表是否正在播放
*/
public boolean isBackgroundMusicPlaying() {
boolean ret = false;
if (mBackgroundMediaPlayer == null) {
ret = false;
} else {
ret = mBackgroundMediaPlayer.isPlaying();
}
return ret;
}

/**
* 结束背景音乐,并释放资源
*/
public void end() {
if (mBackgroundMediaPlayer != null) {
mBackgroundMediaPlayer.release();
}
// 重新“初始化数据”
initData();
}

/**
* 得到背景音乐的“音量”
*
* @return
*/
public float getBackgroundVolume() {
if (this.mBackgroundMediaPlayer != null) {
return (this.mLeftVolume + this.mRightVolume) / 2;
} else {
return 0.0f;
}
}

/**
* 设置背景音乐的音量
*
* @param volume
* :设置播放的音量,float类型
*/
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: