音乐播放

在Activity中创建对象时传入要播放的音乐地址列表,即可顺序或循环播放。

List<String> audioList = new ArrayList<String>();

AudioPlayer audio = new AudioPlayer(audioList,false);
//开始播放

audio.start();

//停止播放

audio.stop();

代码如下:

  1 package com.farben.ams.widget;
2
3 import java.util.List;
4
5 import android.media.MediaPlayer;
6 import android.media.MediaPlayer.OnCompletionListener;
7 import android.media.MediaPlayer.OnErrorListener;
8 import android.util.Log;
9
10
11 /**
12 * 播放背景音乐
13 * @package com.farben.ams.widget
14 * @author Keynes Cao
15 * @create 2011-12-7 下午1:56:06 *
16 */
17 public class AudioPlayer{
18 /**
19 * 歌曲地址列表
20 */
21 private List<String> mList = null;
22 /**
23 * 播放模式
24 */
25 private boolean mMode = true;
26
27 /**
28 * 媒体播放对象
29 */
30 private MediaPlayer mMediaPlayer = null;
31 /**
32 *播放索引
33 */
34 private int currentListItem = 0;
35
36 /**
37 * @param list
38 * <see>歌曲地址列表</see>
39 * @param mode
40 * <see>播放模式,默认 true 循环播放列表,false:只播放列表一次</see>
41 */
42 public AudioPlayer(List<String> mList, boolean mMode) {
43 this(mList);
44 this.mMode = mMode;
45 }
46
47 /**
48 * @param list
49 * <see>歌曲地址列表</see>
50 */
51 public AudioPlayer(List<String> mList) {
52 super();
53 this.mList = mList;
54 mMediaPlayer = new MediaPlayer();
55 }
56 /**
57 * <see>开启播放</see>
58 */
59 public void start(){
60 if(mList != null && mList.size() > 0){
61 playMusic(mList.get(currentListItem));
62 }
63 }
64 /**
65 * <see>停止播放</see>
66 */
67 public void stop(){
68 if(mMediaPlayer != null){
69 //停止播放
70 mMediaPlayer.stop();
71 //资源回收
72 mMediaPlayer.release();
73 mMediaPlayer = null;
74 }
75 }
76
77 /**
78 * @param path
79 * <see>播放指定的歌曲</see>
80 */
81 private void playMusic(String path){
82 try{
83 //重置到空闲状态
84 mMediaPlayer.reset();
85 //设置要播放的内容
86 mMediaPlayer.setDataSource(path);
87 //播放前准备
88 mMediaPlayer.prepare();
89 //开始播放
90 mMediaPlayer.start();
91 //注册监听事件
92 mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
93 public void onCompletion(MediaPlayer arg0) {
94 //下一首
95 nextNext();
96 }
97 });
98 mMediaPlayer.setOnErrorListener(new OnErrorListener() {
99 public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
100 //发生错误时恢复到空闲状态
101 mMediaPlayer.reset();
102 return false;
103 }
104 });
105 }catch(Exception ex){
106 Log.e("AudioPlayer",ex.getMessage()+"\n"+ex);
107 }
108 }
109 /**
110 *下一首歌曲
111 */
112 private void nextNext(){
113 if(++currentListItem >= mList.size()){
114 currentListItem = 0;
115 if(!ismMode()){//非循环模式,播放完后退出
116 stop();
117 return;
118 }
119 }
120 playMusic(mList.get(currentListItem));
121 }
122
123 public boolean ismMode() {
124 return mMode;
125 }
126
127 public void setmMode(boolean mMode) {
128 this.mMode = mMode;
129 }
130 }

 

你可能感兴趣的:(音乐)