通过参照网上其他人的MP3播放器,自己也在这些基础上小试牛刀,制作的了一个MP3的播放器,先上个界面先:
接下来就上代码:
首先是.mp3格式的音乐文件的过滤类单独在一个java文件中:
- package com.example.mediaplayer;
- import java.io.File;
- import java.io.FilenameFilter;
- public class MusicFilter implements FilenameFilter{
- @Override
- public boolean accept(File dir, String filename) {
- // TODO Auto-generated method stub
- return (filename.endsWith(".mp3"));
- }
- }
下面是MainActivity.java中的代码(其中音量和播放进度的方法是参照网上别人的):
- package com.example.mediaplayer;
- import java.io.File;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import android.media.AudioManager;
- import android.os.Bundle;
- import android.annotation.SuppressLint;
- import android.app.ListActivity;
- import android.content.Intent;
- import android.view.KeyEvent;
- import android.view.Menu;
- import android.view.MenuItem;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.ImageButton;
- import android.widget.ListView;
- import android.widget.SeekBar;
- import android.widget.SimpleAdapter;
- import android.widget.Toast;
- public class MainActivity extends ListActivity {
- public static ImageButton start_btn;
- private ImageButton last_btn;
- private ImageButton next_btn;
- public static SeekBar progressBar;
- private SeekBar volumeBar;
- public static List<Map<String, Object>> mList= new ArrayList<Map<String,Object>>();
- public static int currentListItem=0;//当前播放歌曲的索引
- @SuppressLint("SdCardPath")
- public static String MUSIC_PATH = new String("/mnt/sdcard/Music/");
- public static AudioManager audioManager=null;
- private String[] mFrom=new String[]{"img","music_name"};
- private int[] mTo=new int[]{R.id.img, R.id.music_name};
- protected void onCreate(Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- musicList();
- init();
- }
- /*初始化Button*/
- private void init(){
- next_btn= (ImageButton) this.findViewById(R.id.next_btn);
- next_btn.setOnClickListener(btnListen);
- start_btn = (ImageButton) this.findViewById(R.id.start_btn);
- start_btn.setOnClickListener(btnListen);
- last_btn= (ImageButton) this.findViewById(R.id.last_btn);
- last_btn.setOnClickListener(btnListen);
- volumeBar=(SeekBar) this.findViewById(R.id.volume_seekBar);
- progressBar =(SeekBar) this.findViewById(R.id.progressBar);
- /*进度条监听*/
- progressBar.setOnSeekBarChangeListener(new ProgressBarChange());
- /*退出后再次进去程序时,进度条保持持续更新*/
- if(PlayerService.mediaPlayer!=null){
- //设置进度条最大值
- MainActivity.progressBar.setMax(PlayerService.mediaPlayer.getDuration());
- progressBar.setProgress(PlayerService.mediaPlayer.getCurrentPosition());
- }
- audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
- /* 把当前音量值赋给进度条 */
- volumeBar.setProgress(audioManager .getStreamVolume(AudioManager.STREAM_MUSIC));
- /* 监听音量 */
- volumeBar.setOnSeekBarChangeListener(new VolumeBarChang());
- }
- /*设置按键监听*/
- private OnClickListener btnListen = new OnClickListener() {
- @Override
- public void onClick(View v) {
- switch (v.getId()) {
- case R.id.start_btn:
- {
- if(PlayerService.mediaPlayer.isPlaying()){
- playMusic(AppConstant.PlayerMag.PAUSE);
- start_btn.setImageDrawable(getResources().getDrawable(R.drawable.pause_round));
- }else{
- playMusic(AppConstant.PlayerMag.PLAY);
- start_btn.setImageDrawable(getResources().getDrawable(R.drawable.play_round));
- }
- }
- break;
- case R.id.next_btn:
- nextMusic();
- break;
- case R.id.last_btn:
- frontMusic();
- break;
- default:
- break;
- }
- }
- };
- /*显示歌曲到listView*/
- public void musicList(){
- File home= new File(MUSIC_PATH);
- File[] files=home.listFiles(new MusicFilter());
- Map<String,Object> mMap = null;
- mList.clear();
- if(files.length > 0){
- for(File f:files){
- mMap = new HashMap<String,Object>();
- mMap.put("img", R.drawable.music_round);
- mMap.put("music_name", f.getName());
- mList.add(mMap);
- }
- }
- SimpleAdapter mAdapter = new SimpleAdapter(this, mList, R.layout.item, mFrom, mTo);
- setListAdapter(mAdapter);
- }
- //播放音乐
- public void playMusic(int action){
- Intent intent = new Intent();
- intent.putExtra("CMD", action);
- intent.putExtra("ITEM", currentListItem);
- intent.setClass(MainActivity.this, PlayerService.class);
- startService(intent);
- }
- //下一首
- public void nextMusic(){
- if (++currentListItem >= mList.size()) {
- Toast.makeText(MainActivity.this, "已到最后一首歌曲", Toast.LENGTH_SHORT) .show();
- currentListItem = mList.size() - 1;
- } else {
- playMusic(AppConstant.PlayerMag.PLAY);
- }
- }
- //上一首
- public void frontMusic(){
- if (--currentListItem > 0) {
- playMusic(AppConstant.PlayerMag.PLAY);
- } else {
- Toast.makeText(MainActivity.this, "已到第一首歌曲", Toast.LENGTH_SHORT)
- .show();
- currentListItem = 0;
- }
- }
- /* 音乐选择监听
- * 用户点击listview的栏目,直接播放
- * */
- @Override
- protected void onListItemClick(ListView l, View v, int position, long id) {
- currentListItem = position;
- playMusic(AppConstant.PlayerMag.PLAY);
- }
- @Override
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- // TODO Auto-generated method stub
- if(keyCode == KeyEvent.KEYCODE_BACK){
- this.finish();
- }
- return super.onKeyDown(keyCode, event);
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- // TODO Auto-generated method stub
- getMenuInflater().inflate(R.menu.main, menu);
- return true;
- }
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- // TODO Auto-generated method stub
- if(item.getItemId() == R.id.exit){
- Intent intent = new Intent();
- intent.setClass(MainActivity.this, PlayerService.class);
- stopService(intent);//停止Service
- MainActivity.this.finish();
- }
- return super.onOptionsItemSelected(item);
- }
- }
其中进度和音量的实现如下:
- package com.example.mediaplayer;
- import android.widget.SeekBar;
- /*
- * 播放进度监听
- * */
- public class ProgressBarChange implements SeekBar.OnSeekBarChangeListener{
- @Override
- public void onProgressChanged(SeekBar seekBar, int progress,
- boolean fromUser) {
- // TODO Auto-generated method stub
- // 当进度条的值改变时,音乐播放器从新的位置开始播放
- if(fromUser){
- PlayerService.mediaPlayer.seekTo(progress);
- }
- }
- @Override
- public void onStartTrackingTouch(SeekBar seekBar) {
- // TODO Auto-generated method stub
- PlayerService.mediaPlayer.pause(); // 开始拖动进度条时,音乐暂停播放
- }
- @Override
- public void onStopTrackingTouch(SeekBar seekBar) {
- // TODO Auto-generated method stub
- PlayerService.mediaPlayer.start();// 停止拖动进度条时,音乐开始播放
- }
- }
- package com.example.mediaplayer;
- import android.media.AudioManager;
- import android.widget.SeekBar;
- /*
- * 音量监听
- * */
- public class VolumeBarChang implements SeekBar.OnSeekBarChangeListener{
- @Override
- public void onProgressChanged(SeekBar seekBar, int progress,
- boolean fromUser) {
- // TODO Auto-generated method stub
- MainActivity.audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress,
- 0);
- }
- @Override
- public void onStartTrackingTouch(SeekBar seekBar) {
- // TODO Auto-generated method stub
- }
- @Override
- public void onStopTrackingTouch(SeekBar seekBar) {
- // TODO Auto-generated method stub
- }
- }
最后就是service部分的了:
- package com.example.mediaplayer;
- import java.io.IOException;
- import java.util.Map;
- import android.app.Service;
- import android.content.Intent;
- import android.media.MediaPlayer;
- import android.os.IBinder;
- import android.widget.Toast;
- public class PlayerService extends Service implements Runnable,
- MediaPlayer.OnCompletionListener{
- public static MediaPlayer mediaPlayer=null;
- private static boolean isLoop=false;
- private String path = null;
- private int CMD;
- @Override
- public void onCreate() {
- // TODO Auto-generated method stub
- super.onCreate();
- if(mediaPlayer != null){
- mediaPlayer.reset();
- mediaPlayer.release();
- mediaPlayer=null;
- }
- mediaPlayer=new MediaPlayer();
- mediaPlayer.setOnCompletionListener(this);
- }
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- // TODO Auto-generated method stub
- CMD=(int)intent.getIntExtra("CMD", AppConstant.PlayerMag.PLAY);
- if(CMD == AppConstant.PlayerMag.PLAY){
- playMusic((int)intent.getIntExtra("ITEM",MainActivity.currentListItem));
- }else if(CMD == AppConstant.PlayerMag.PAUSE){
- if(mediaPlayer.isPlaying()){
- mediaPlayer.pause();
- }else {
- mediaPlayer.start();
- }
- }
- new Thread(this).start();//进度条开始
- return super.onStartCommand(intent, flags, startId);
- }
- public void playMusic(int item) {
- try {
- Map<String, Object> map = MainActivity.mList.get(item);
- path=MainActivity.MUSIC_PATH+map.get("music_name");
- mediaPlayer.reset();
- mediaPlayer.setDataSource(path);
- mediaPlayer.prepare();
- mediaPlayer.start();
- mediaPlayer.setLooping(isLoop);
- MainActivity.progressBar.setMax(PlayerService.mediaPlayer.getDuration());//设置播放进度条的最大值
- } catch (IllegalArgumentException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (SecurityException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IllegalStateException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- @Override
- public IBinder onBind(Intent intent) {
- // TODO Auto-generated method stub
- return null;
- }
- @Override
- public void onDestroy() {
- // TODO Auto-generated method stub
- super.onDestroy();
- if(mediaPlayer != null){
- mediaPlayer.stop();
- mediaPlayer.release();
- mediaPlayer=null;
- }
- }
- @Override
- public void run() {
- int currentPosition = 0;// 设置默认进度条当前位置
- int total = mediaPlayer.getDuration();//
- while (mediaPlayer != null && currentPosition < total) {
- try {
- Thread.sleep(1000);
- if (mediaPlayer != null) {
- currentPosition = mediaPlayer.getCurrentPosition();
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- MainActivity.progressBar.setProgress(currentPosition);
- }
- }
- @Override
- public void onCompletion(MediaPlayer mp) {
- /*当前歌曲播放完,自动播放跳到下一首*/
- if (++MainActivity.currentListItem >= MainActivity.mList.size()) {
- Toast.makeText(PlayerService.this, "已到最后一首歌曲", Toast.LENGTH_SHORT)
- .show();
- MainActivity.currentListItem--;
- MainActivity.progressBar.setMax(0);
- } else {
- playMusic(MainActivity.currentListItem);
- }
- MainActivity.start_btn.setImageDrawable(getResources().getDrawable(R.drawable.play_round));
- }
- }
业余时间第一次去做算是比较完整小应用,其中学到真的还是很多的,其中很多是在blog的各大神中学的,
所以自己也要把这次发布出来,希望各位大神级的多多指点下我这种菜鸟。