Android Studio实现简单音乐播放功能的示例代码
项目要求
基于Broadcast,BroadcastReceiver等与广播相关的知识实现简单的音乐播放功能,包括音乐的播放、暂停、切换、进度选择、音量调整。
设计效果
(进度条时间刷新功能还没有实现)
实现思路
音乐服务端负责播放音乐和收发广播的功能。当音乐服务端作为接收器时,只能接收到主页面广播的控制消息;作为发送器时,向主页面发送歌曲信息更新的消息 主页面负责进度条以及音量按钮的监听,同时也有收发广播的功能。当主页面作为接收器时,只能接收到音乐服务端广播的歌曲信息更新的消息;作为发送器时,向音乐服务端发送对歌曲播放的控制消息。项目结构图
主要代码
1 主页面
package com.example.dell.musicbox3;import android.app.Activity;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.media.AudioManager;import android.os.Bundle;import android.view.View;import android.view.Window;import android.widget.ImageButton;import android.widget.SeekBar;import android.widget.TextView;public class MainActivity extends Activity implements View.OnClickListener{// 获取界面中显示歌曲标题、作者文本框TextView title, author;// 播放/暂停、停止按钮ImageButton play, next, last;// 声明音量管理器public AudioManager mAudioManager = null;// 定义进度条public static SeekBar audioSeekBar = null;// 定义音量大小public SeekBar audioVolume = null;ActivityReceiver activityReceiver;public static final String CTL_ACTION = 'org.crazyit.action.CTL_ACTION';public static final String UPDATE_ACTION = 'org.crazyit.action.UPDATE_ACTION';// 定义音乐的播放状态,0x11代表没有播放;0x12代表正在播放;0x13代表暂停int status = 0x11;String[] titleStrs = new String[] { '龙卷风', '可爱女人', '星晴' };String[] authorStrs = new String[] { 'JayChou', 'JayChou', 'JayChou' };@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);setContentView(R.layout.layout);// 获取程序界面界面中的两个按钮play = (ImageButton) this.findViewById(R.id.play);last = (ImageButton) this.findViewById(R.id.last);next = (ImageButton) this.findViewById(R.id.next);audioVolume = (SeekBar) findViewById(R.id.seekBar2);audioSeekBar = (SeekBar) findViewById(R.id.seekBar1);title = (TextView) findViewById(R.id.title);author = (TextView) findViewById(R.id.author);// 为两个按钮的单击事件添加监听器play.setOnClickListener(this);last.setOnClickListener(this);next.setOnClickListener(this);// 播放进度监听audioSeekBar.setOnSeekBarChangeListener(new SeekBarChangeEvent());// 退出后再次进去程序时,进度条保持持续更新if (MusicService.mPlayer != null) {// 设置进度条的最大值MainActivity.audioSeekBar.setMax(MusicService.mPlayer.getDuration());audioSeekBar.setProgress(MusicService.mPlayer.getCurrentPosition());}// 得到当前音量对象mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);// 把当前音量值赋给进度条audioVolume.setProgress(mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC));// 监听音量audioVolume.setOnSeekBarChangeListener(new AudioVolumeChangeEvent());activityReceiver = new ActivityReceiver();// 创建IntentFilterIntentFilter filter = new IntentFilter();// 指定BroadcastReceiver监听的Actionfilter.addAction(UPDATE_ACTION);// 注册BroadcastReceiverregisterReceiver(activityReceiver, filter);Intent intent = new Intent(this, MusicService.class);// 启动后台ServicestartService(intent);}// 音量监听class AudioVolumeChangeEvent implements SeekBar.OnSeekBarChangeListener {@Overridepublic void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress,0);}@Overridepublic void onStartTrackingTouch(SeekBar seekBar) {}@Overridepublic void onStopTrackingTouch(SeekBar seekBar) {}}// 播放进度监听,别忘了Service里面还有个进度条刷新class SeekBarChangeEvent implements SeekBar.OnSeekBarChangeListener {@Overridepublic void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {// 假设改变源于用户拖动if (fromUser) {MusicService.mPlayer.seekTo(progress);// 当进度条的值改变时,音乐播放器从新的位置开始播放}}@Overridepublic void onStartTrackingTouch(SeekBar seekBar) {MusicService.mPlayer.pause();}@Overridepublic void onStopTrackingTouch(SeekBar seekBar) {MusicService.mPlayer.start();}}// 自定义的BroadcastReceiver,负责监听从Service传回来的广播public class ActivityReceiver extends BroadcastReceiver{@Overridepublic void onReceive(Context context, Intent intent){// 获取Intent中的update消息,update代表播放状态int update = intent.getIntExtra('update', -1);// 获取Intent中的current消息,current代表当前正在播放的歌曲int current = intent.getIntExtra('current', -1);if (current >= 0){title.setText(titleStrs[current]);author.setText(authorStrs[current]);}switch (update){case 0x11:play.setImageResource(R.drawable.play);status = 0x11;break;// 控制系统进入播放状态case 0x12:// 播放状态下设置使用暂停图标play.setImageResource(R.drawable.pause);// 设置当前状态status = 0x12;break;// 控制系统进入暂停状态case 0x13:// 暂停状态下设置使用播放图标play.setImageResource(R.drawable.play);// 设置当前状态status = 0x13;break;}}}@Overridepublic void onClick(View source){// 创建IntentIntent intent = new Intent('org.crazyit.action.CTL_ACTION');switch (source.getId()){// 按下播放/暂停按钮case R.id.play:intent.putExtra('control', 1);break;case R.id.last:intent.putExtra('control', 2);break;//按下上一首按钮case R.id.next:intent.putExtra('control', 3);break;}// 发送广播,将被Service组件中的BroadcastReceiver接收到sendBroadcast(intent);}}
2 音乐服务端
package com.example.dell.musicbox3;import java.io.IOException;import android.app.Service;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.content.res.AssetFileDescriptor;import android.content.res.AssetManager;import android.media.MediaPlayer;import android.media.MediaPlayer.OnCompletionListener;import android.os.IBinder;public class MusicService extends Service implements Runnable{MyReceiver serviceReceiver;//asset文件管理对象AssetManager am;String[] musics = new String[] { '周杰?? - 龙卷风.mp3', '周杰?? - 星晴.mp3', '周杰?? - 可爱女人.mp3' };public static MediaPlayer mPlayer;// 当前的状态,0x11代表没有播放;0x12代表正在播放;0x13代表暂停int status = 0x11;// 记录当前正在播放的音乐int current = 0;@Override//非绑定式服务public IBinder onBind(Intent intent){return null;}@Override//定义初始化函数public void onCreate(){super.onCreate();//获取asset文件夹里的所有歌曲am = getAssets();// 创建具有筛选功能的服务端接收器serviceReceiver = new MyReceiver();// 创建IntentFilter过滤器IntentFilter filter = new IntentFilter();//使音乐服务端的接收器只能接收客户端发来的CTL_ACTION消息filter.addAction(MainActivity.CTL_ACTION);//注册带有此筛选器且名字叫做serviceReceiver的接收器registerReceiver(serviceReceiver, filter);// 创建MediaPlayermPlayer = new MediaPlayer();// 为MediaPlayer播放完成事件绑定监听器mPlayer.setOnCompletionListener(new OnCompletionListener() // ①{@Overridepublic void onCompletion(MediaPlayer mp){current++;if (current >= 3){current = 0;}//发送广播通知Activity更改文本框Intent sendIntent = new Intent(MainActivity.UPDATE_ACTION);sendIntent.putExtra('current', current);// 发送广播,将被Activity组件中的BroadcastReceiver接收到sendBroadcast(sendIntent);// 准备并播放音乐prepareAndPlay(musics[current]);}});}public class MyReceiver extends BroadcastReceiver{@Overridepublic void onReceive(final Context context, Intent intent){int control = intent.getIntExtra('control', -1);switch (control){// 播放或暂停case 1:// 原来处于没有播放状态if (status == 0x11){// 准备并播放音乐prepareAndPlay(musics[current]);status = 0x12;}// 原来处于播放状态else if (status == 0x12){// 暂停mPlayer.pause();// 改变为暂停状态status = 0x13;}// 原来处于暂停状态else if (status == 0x13){// 播放mPlayer.start();// 改变状态status = 0x12;}break;// 停止声音case 2://上一首切换if (current <= 0) {//停止播放mPlayer.stop();//修改currentcurrent = musics.length-1;//播放prepareAndPlay(musics[current]);status = 0x12;}else{mPlayer.stop();current--;prepareAndPlay(musics[current]);status = 0x12;}break;//下一首切换case 3:if (current >= 2) {mPlayer.stop();current = 0;prepareAndPlay(musics[current]);status = 0x12;}else{mPlayer.stop();current++;prepareAndPlay(musics[current]);status = 0x12;}break;}// 广播通知Activity更改图标、文本框Intent sendIntent = new Intent(MainActivity.UPDATE_ACTION);sendIntent.putExtra('update', status);sendIntent.putExtra('current', current);// 发送广播,将被Activity组件中的BroadcastReceiver接收到sendBroadcast(sendIntent);}}private void prepareAndPlay(String music) {try {// 打开指定音乐文件AssetFileDescriptor afd = am.openFd(music);mPlayer.reset();// 使用MediaPlayer加载指定的声音文件。mPlayer.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(), afd.getLength());// 准备声音mPlayer.prepare();// 播放mPlayer.start();// 设置进度条最大值MainActivity.audioSeekBar.setMax(MusicService.mPlayer.getDuration());new Thread(this).start();} catch (IOException e) {e.printStackTrace();}}// 刷新进度条public void run() {int CurrentPosition = 0;int total = mPlayer.getDuration();while (mPlayer != null && CurrentPosition < total) {try {Thread.sleep(1000);if (mPlayer != null) {CurrentPosition = mPlayer.getCurrentPosition();}} catch (InterruptedException e) {e.printStackTrace();}MainActivity.audioSeekBar.setProgress(CurrentPosition);}}}
仓库链接
MusicBox
到此这篇关于Android Studio实现简单音乐播放功能的示例代码的文章就介绍到这了,更多相关Android Studio 音乐播放内容请搜索好吧啦网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好吧啦网!
相关文章: