Android开发之音乐播放器的实现

时间:2023-03-09 01:35:27
Android开发之音乐播放器的实现

Android音乐播放器

使用到Android的Actiivity和Service组件

播放音频的代码应该运行在服务中,定义一个播放服务MusicService,服务里定义play、stop、pause、continuePlay等方法

把这几个方法抽取成一个接口MusicInterface

定义一个中间人类,继承Binder,实现MusicInterface

操作按钮等使用Activity与用户交互

同时为了把服务所在进程变成服务进程,防止Activity销毁时依旧执行Service,需要使用Service启动的混合调用,即先使用startService(),然后使用bindService()方法。

原理:使用bindService()方法,启动service。在ServiceConnection的onServiceConnected()方法中返回一个iBinder对象,通过该对象可以操作音乐service中的播放音乐的方法。

播放服务

代码:

MainActivity:

 import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.View;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener; public class MainActivity extends Activity { private MusicInterface mi; static Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
Bundle bundle = msg.getData();
//取出消息携带的数据
int duration = bundle.getInt("duration");
int currentPosition = bundle.getInt("currentPosition");
//刷新播放进度
sb.setMax(duration);
sb.setProgress(currentPosition);
};
}; private static SeekBar sb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sb = (SeekBar) findViewById(R.id.sb);
//给sb设置一个拖动侦听
sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
//停止拖动时调用
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
//根据拖动进度,改变音乐播放进度
mi.seekTo(seekBar.getProgress());
}
//开始拖动时调用
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub }
//拖动的时候不断调用
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub }
});
Intent intent = new Intent(this, MusicService.class);
//先start启动MusicService,再bind
startService(intent);
MyServiceConn conn = new MyServiceConn();
bindService(intent, conn, BIND_AUTO_CREATE);
} class MyServiceConn implements ServiceConnection { @Override
public void onServiceConnected(ComponentName name, IBinder service) {
mi = (MusicInterface) service;
} @Override
public void onServiceDisconnected(ComponentName name) { } } public void play(View v) {
mi.play();
} public void continuePlay(View v) {
mi.continuePlay();
} public void pause(View v) {
mi.pause();
} public void stop(View v) {
mi.stop();
}
}

MusicService:

 import java.util.Timer;
import java.util.TimerTask; import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message; public class MusicService extends Service {
private MediaPlayer player;
private Timer timer; @Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return new MusicMiddleMan();
} class MusicMiddleMan extends Binder implements MusicInterface {
public void play() {
MusicService.this.play();
} public void pause() {
MusicService.this.pause();
} public void continuePlay() {
MusicService.this.continuePlay();
} public void stop() {
MusicService.this.stop();
} @Override
public void seekTo(int progress) {
// TODO Auto-generated method stub
MusicService.this.seekTo(progress);
} } @Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
player = new MediaPlayer(); } public void play() {
System.out.println("播放");
if (player == null) {
player = new MediaPlayer();
}
player.reset();
try {
//设置网络资源
player.setDataSource("http://192.168.5.100:8080/HEYJUDE.mp3");
// 异步获取网络资源
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() { @Override
public void onPrepared(MediaPlayer mp) {
player.start();
addTimer(); }
});
} catch (Exception e) {
e.printStackTrace();
} } public void continuePlay() {
System.out.println("继续播放");
player.start();
} public void pause() {
System.out.println("暂停");
player.pause();
} public void stop() {
System.out.println("停止");
player.stop();
player.release();
player = null;
if (timer!=null) {
timer.cancel();
timer=null;
}
} public void seekTo(int progress){
player.seekTo(progress);
} public void addTimer() {
//播放进度需要不停的获取,不停的刷新进度条,使用计时器每1000毫秒获取一次播放进度
//发消息至Handler,把播放进度放进Message对象中,在Handler中更新SeekBar的进度
if (timer == null) { timer = new Timer();
timer.schedule(new TimerTask() { @Override
public void run() {
// 获取到歌曲总时长
int duration = player.getDuration();
// 获取歌曲当前进度
int currentPosition = player.getCurrentPosition();
Message msg = MainActivity.handler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putInt("duration", duration);
bundle.putInt("currentPosition", currentPosition);
msg.setData(bundle);
MainActivity.handler.sendMessage(msg); }
}, 5, 1000);
} } }

把MusicControl类抽取出来为接口,这样可以在MainActivity中只可以访问接口的方法,MusicControl类中的其他方法不被方法

MusicInterface:

 public interface MusicInterface {

     void play();
void continuePlay();
void stop();
void pause();
void seekTo(int progress); }