写一个音乐播放器,可以实现播放、暂停、停止、上一曲、下一曲,进度条拖动等功能,这个程序写的缺陷比较大,只能播放特定文件夹里面的特定的歌曲文件,一定要记得添加权限和注册服务
1.记得添加权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
2.添加服务
<service
android:name="com.wsine.west.exp5_AfterClass.MusicService"
android:exported="true" />
3.界面布局
<SeekBar
android:id="@+id/MusicSeekBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
4.主界面调用
package com.exameple.zmusic;
import java.text.SimpleDateFormat;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
public class MainActivity extends Activity implements View.OnClickListener {
private MusicService musicService;
private SeekBar seekBar;
private TextView musicStatus, musicTime;
private Button btnPlayOrPause, btnStop, btnQuit;
private SimpleDateFormat time = new SimpleDateFormat("m:ss");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("hint", "ready to new MusicService");
musicService = new MusicService();
Log.d("hint", "finish to new MusicService");
bindServiceConnection();
seekBar = (SeekBar) this.findViewById(R.id.MusicSeekBar);
seekBar.setProgress(musicService.mp.getCurrentPosition());
seekBar.setMax(musicService.mp.getDuration());
musicStatus = (TextView) this.findViewById(R.id.MusicStatus);
musicTime = (TextView) this.findViewById(R.id.MusicTime);
btnPlayOrPause = (Button) this.findViewById(R.id.BtnPlayorPause);
Log.d("hint", Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/You.mp3");
}
private ServiceConnection sc = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName,
IBinder iBinder) {
musicService = ((MusicService.MyBinder) iBinder).getService();
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
musicService = null;
}
};
private void bindServiceConnection() {
Intent intent = new Intent(MainActivity.this, MusicService.class);
startService(intent);
bindService(intent, sc, this.BIND_AUTO_CREATE);
}
public android.os.Handler handler = new android.os.Handler();
public Runnable runnable = new Runnable() {
@Override
public void run() {
if (musicService.mp.isPlaying()) {
musicStatus.setText(getResources().getString(R.string.playing));
btnPlayOrPause.setText(getResources().getString(R.string.pause)
.toUpperCase());
} else {
musicStatus.setText(getResources().getString(R.string.pause));
btnPlayOrPause.setText(getResources().getString(R.string.play)
.toUpperCase());
}
musicTime.setText(time.format(musicService.mp.getCurrentPosition())
+ "/" + time.format(musicService.mp.getDuration()));
seekBar.setProgress(musicService.mp.getCurrentPosition());
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (fromUser) {
musicService.mp.seekTo(seekBar.getProgress());
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
handler.postDelayed(runnable, 100);
}
};
@Override
protected void onResume() {
if (musicService.mp.isPlaying()) {
musicStatus.setText(getResources().getString(R.string.playing));
} else {
musicStatus.setText(getResources().getString(R.string.pause));
}
seekBar.setProgress(musicService.mp.getCurrentPosition());
seekBar.setMax(musicService.mp.getDuration());
handler.post(runnable);
super.onResume();
Log.d("hint", "handler post runnable");
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.BtnPlayorPause:
musicService.playOrPause();
break;
case R.id.BtnStop:
musicService.stop();
seekBar.setProgress(0);
break;
case R.id.BtnQuit:
handler.removeCallbacks(runnable);
unbindService(sc);
try {
System.exit(0);
} catch (Exception e) {
e.printStackTrace();
}
break;
case R.id.btnPre:
musicService.preMusic();
break;
case R.id.btnNext:
musicService.nextMusic();
break;
default:
break;
}
}
@Override
public void onDestroy() {
unbindService(sc);
super.onDestroy();
}
}
5.服务类
package com.exameple.zmusic;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
/**
*/
public class MusicService extends Service {
private String[] musicDir = new String[]{Environment.getExternalStorageDirectory().getAbsolutePath()+"/Music/梦里水乡.mp3",
Environment.getExternalStorageDirectory().getAbsolutePath()+"/Music/你的样子.mp3",
Environment.getExternalStorageDirectory().getAbsolutePath()+"/Music/偏偏喜欢你.mp3",
Environment.getExternalStorageDirectory().getAbsolutePath() +"/Music/一剪梅.mp3"};
private int musicIndex = 1;
public final IBinder binder = new MyBinder();
public static MediaPlayer mp = new MediaPlayer();
public class MyBinder extends Binder{
MusicService getService() {
return MusicService.this;
}
}
public MusicService() {
try {
mp.setDataSource(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Music/大约在冬季.mp3");
//mp.setDataSource(Environment.getDataDirectory().getAbsolutePath()+"/You.mp3");
mp.prepare();
musicIndex = 1;
} catch (Exception e) {
Log.d("hint","can't get to the song");
e.printStackTrace();
}
}
public void playOrPause() {
if(mp.isPlaying()){
mp.pause();
} else {
mp.start();
}
}
public void stop() {
if(mp != null) {
mp.stop();
try {
mp.prepare();
mp.seekTo(0);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void nextMusic() {
if(mp != null && musicIndex < 3) {
mp.stop();
try {
mp.reset();
mp.setDataSource(musicDir[musicIndex+1]);
musicIndex++;
mp.prepare();
mp.seekTo(0);
mp.start();
} catch (Exception e) {
Log.d("hint", "can't jump next music");
e.printStackTrace();
}
}
}
public void preMusic() {
if(mp != null && musicIndex > 0) {
mp.stop();
try {
mp.reset();
mp.setDataSource(musicDir[musicIndex-1]);
musicIndex--;
mp.prepare();
mp.seekTo(0);
mp.start();
} catch (Exception e) {
Log.d("hint", "can't jump pre music");
e.printStackTrace();
}
}
}
@Override
public void onDestroy() {
mp.stop();
mp.release();
super.onDestroy();
}
/**
* onBind 是 Service 的虚方法,因此我们不得不实现它。
* 返回 null,表示客服端不能建立到此服务的连接。
*/
@Override
public IBinder onBind(Intent intent) {
return binder;
}
}