Android Studio实现简单的音乐播放

1,324 阅读2分钟

目的:

    制作一个简单的音乐播放器,实现音乐播放/暂停,换曲,进度条控制的功能。

工具:

   Android Studio

原理:

   在Android中,广播(Broadcast)是一种广泛运用在应用程序之间传输信息的机制。广播的消息实质就是将一个Intent对象使用方法发sendBroadcast()送出去。BroadcastReceiver是对发送出来的Broadcast进行过滤接受并响应的一类组件,是Android系统的四大组件之一。

具体过程:

   UI设计

设计期望是有一个播放图片,一个进度条,四个控制按钮,故做如下设计

<ImageView   
android:id="@+id/imageView"   
android:layout_width="match_parent"   
android:layout_height="260dp"   
android:contentDescription="@string/app_name"   
android:src="@drawable/music"/><SeekBar   
android:id="@+id/seekBar1"   
android:layout_width="match_parent"   
android:layout_height="wrap_content" />
<LinearLayout   
android:layout_width="match_parent"   
android:layout_height="match_parent"   
android:orientation="vertical">   
<TextView      
android:id="@+id/title"      
android:layout_width="match_parent"      
android:layout_height="40sp"      
android:gravity="center"      
android:textSize="20sp" />   
<TextView      
android:id="@+id/author"      
android:layout_width="match_parent"      
android:layout_height="40sp"      
android:gravity="center"      
android:textSize="20sp" />
</LinearLayout><LinearLayout   
android:id="@+id/rl"   
android:layout_width="match_parent"   
android:layout_height="wrap_content"   
android:layout_marginBottom="20dp"   
android:gravity="center"   
android:orientation="horizontal">   
<ImageButton      
android:id="@+id/last"      
android:layout_width="wrap_content"      
android:layout_height="match_parent"      
android:layout_weight="1"      
android:background="#F9FAFA"      
android:scaleType="center"      
android:contentDescription="@string/app_name"      
android:src="@drawable/last" />   
<ImageButton      
android:id="@+id/play"      
android:layout_width="wrap_content"      
android:layout_height="wrap_content"      
android:layout_weight="1"      
android:background="#F9FAFA"      
android:contentDescription="@string/app_name"      
android:src="@drawable/pause" />   
<ImageButton      
android:id="@+id/stop"      
android:layout_width="112dp"      
android:layout_height="match_parent"      
android:background="#F9FAFA"      
android:contentDescription="@string/app_name"      
android:src="@drawable/stop" />   
<ImageButton      
android:id="@+id/next"      
android:layout_width="wrap_content"      
android:layout_height="wrap_content"      
android:layout_weight="1"      
android:background="#F9FAFA"      
android:contentDescription="@string/app_name"      
android:src="@drawable/next" />
</LinearLayout>

    功能实现

**    1创建服务类**

  创建MusicService文件,点击包名——>New——>Service——>Service,如图:

 ** 1.1实现功能**

   服务类中要实现的功能有,音乐的播放/暂停,切换,进度条的控制,主要代码如下:

  1.1.1播放,暂停,切换

public class MyReceiver extends BroadcastReceiver{   
@Override   
public 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 (status == 0x12 || status == 0x13)  
 {            
   // 停止播放      
 mPlayer.stop();      
 status = 0x11;            }          
 break;        
 //上一曲        
 case 3:            
 if (current<0) {              
 mPlayer.stop();              
 current = musics.length - 1;              
 prepareAndPlay(musics[current]);               
 status = 0x12;            }            
 else {              
 mPlayer.stop();              
 current--;              
 prepareAndPlay(musics[current]);             
  status = 0x12;            }           
 break;        
 //下一曲         
 case 4:            
 if (current >= musics.length-1)            
{               
 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);   }}

 1.1.2 进度条控制

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();      
}      c
atch (IOException e)     
 {         e.printStackTrace();      }   }   
//刷新进度条   
@Override   
public void run(){      
int i = 0;      
int total = mPlayer.getDuration();     
 while (mPlayer != null && i <total){         
try{            
Thread.sleep(1000);            
if(mPlayer != null){               
i = mPlayer.getCurrentPosition();           
 }         } catch (InterruptedException e)
 {            
e.printStackTrace();         }         
MainActivity.audioSeekBar.setProgress(i);      }   }}

 2音乐播放界面

  主要是一些按钮的控制,主要代码如下:

//播放进度监听   
class SeekBarChangeEvent implements SeekBar.OnSeekBarChangeListener{      
@Override     
 public void onProgressChanged(SeekBar seekBar, int i, boolean b) {         
if(b){            
MusicService.mPlayer.seekTo(i);         }      }      
@Override      
public void onStartTrackingTouch(SeekBar seekBar) {             
MusicService.mPlayer.pause();      }     
 @Override      
public void onStopTrackingTouch(SeekBar seekBar) {        
 MusicService.mPlayer.start();      }   }   
// 自定义的BroadcastReceiver,负责监听从Service传回来的广播   
public class ActivityReceiver extends BroadcastReceiver{   
@Override   public 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.play);            
// 设置当前状态            
status = 0x12;            
break;         
// 控制系统进入暂停状态         
case 0x13:            
// 暂停状态下设置使用播放图标            
play.setImageResource(R.drawable.pause);            
// 设置当前状态            
status = 0x13;            
break;      }   }}   
@Override  
 public void onClick(View source)   
{      
// 创建Intent      
Intent intent = new Intent("org.xr.action.CTL_ACTION");     
 switch (source.getId())      {         
// 按下播放/暂停按钮         
case R.id.play:            
intent.putExtra("control", 1);            
break;         
// 按下停止按钮         
case R.id.stop:            
intent.putExtra("control", 2);            
break;         
//按下上一曲        
 case R.id.last:            
intent.putExtra("control",3);            
break;         
//按下下一曲         
case R.id.next:            
intent.putExtra("control",4);      }     
 // 发送广播,将被Service组件中的BroadcastReceiver接收到      
sendBroadcast(intent);   }}

结果:

至此,设计完成,最后附上具体代码:

gitee.com/wx_818382bd…