android mediaPlayer 实例 附源码

/**

菜鸟交流学习所作。实现功能:左右滑动换上、下一曲;上下滑动切换音量;点击、双击播放暂停;随机播放与单曲循环;切换播放路径等。

*/

package com.simplemedia;

import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnTouchListener {
 private String  songRootPath,songpath,rootPath = "/mnt/sdcard/", path, currentRootPath = "/mnt/sdcard/";
 private int currentSong = 0, songCount, id = -1;
 boolean isPaused=false,isStopped=false;
 private ListView showPathList;
 public MediaPlayer mediaPlayer;
 GestureDetector detector;
 public AudioManager audioManager;
 TextView songNamText, stateText, showPathText;
 LinearLayout detectorLayout, layoutParent;
 File currentParent;
 File[] currentFiles;
 ImageButton lastSongBtn, nextSongBtn, voicMaxBtn, voiceDefaultBtn,
   voiceMinBtn, cycleBtn, randomBtn, pathBtn, stopBtn, playBtn,
   pauseBtn;
 private List<String> songList = new ArrayList<String>();
 void init() {
  songNamText = (TextView) findViewById(R.id.songNamText);
  playBtn = (ImageButton) findViewById(R.id.playBtn);
  pauseBtn = (ImageButton) findViewById(R.id.pauseBtn);
  stopBtn = (ImageButton) findViewById(R.id.stopBtn);
  cycleBtn = (ImageButton) findViewById(R.id.cycleBtn);
  randomBtn = (ImageButton) findViewById(R.id.randomBtn);
  pathBtn = (ImageButton) findViewById(R.id.pathBtn);
  lastSongBtn = (ImageButton) findViewById(R.id.lastSongBtn);
  nextSongBtn = (ImageButton) findViewById(R.id.nextSongBtn);
  voicMaxBtn = (ImageButton) findViewById(R.id.voicMaxBtn);
  voiceMinBtn = (ImageButton) findViewById(R.id.voiceMinBtn);
  voiceDefaultBtn = (ImageButton) findViewById(R.id.voiceDefaultBtn);
  detectorLayout = (LinearLayout) findViewById(R.id.detectorLayout);
  layoutParent = (LinearLayout) findViewById(R.id.layoutParent);
  mediaPlayer = new MediaPlayer();
  audioManager = (AudioManager) getSystemService(Service.AUDIO_SERVICE);
  songList();
  getSongCount();
 }

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  init();
  detector = new GestureDetector(this, new LearnGestureDetector());
  songNamText.setText("当前无播放歌曲");
  detectorLayout.setOnTouchListener(this);
  voicMaxBtn.setOnClickListener(new ImaBtnClickListener());
  voiceMinBtn.setOnClickListener(new ImaBtnClickListener());
  voiceDefaultBtn.setOnClickListener(new ImaBtnClickListener());
  pathBtn.setOnClickListener(new ImaBtnClickListener());
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }
   
 class LearnGestureDetector extends GestureDetector.SimpleOnGestureListener {

  @Override
  public boolean onDoubleTap(MotionEvent e) {
   // TODO Auto-generated method stub
   Log.e("---", "onDoubleTap");
   return true;
  }

  @Override
  public boolean onDoubleTapEvent(MotionEvent e) {
   // TODO Auto-generated method stub
   Log.e("onDoubleTap+pause()", "---------");
   pauseMeida();
   return true;
  }

  @Override
  public boolean onDown(MotionEvent e) {
   // TODO Auto-generated method stub
   return true;
  }

  @Override
  public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
    float velocityY) {
   // TODO Auto-generated method stub
   // 向左滑动判断
             Log.e("onFling()", "--------");
   if ((e1.getX() - e2.getX()) > 15
     && ((e1.getX() - e2.getX()) > Math.abs(e1.getY()
       - e2.getY()))) {
    nextSong();
   } else if (e2.getX() - e1.getX() > 15
     && ((e2.getX() - e1.getX()) > Math.abs(e1.getY()
       - e2.getY()))) {
    lastSong();
   } else if ((e1.getY() - e2.getY()) > 15
     && ((e1.getY() - e2.getY()) > Math.abs(e1.getX()
       - e2.getX()))) {
    voiceManagerMax();
   } else if ((e2.getY() - e1.getY()) > 15
     && ((e2.getY() - e1.getY()) > Math.abs(e1.getX()
       - e2.getX()))) {
    voiceManagerMin();
   }

   return true;
  }

  @Override
  public void onLongPress(MotionEvent e) {
   // TODO Auto-generated method stub
   super.onLongPress(e);
  }

  @Override
  public boolean onScroll(MotionEvent e1, MotionEvent e2,
    float distanceX, float distanceY) {
   // TODO Auto-generated method stub
   return true;
  }

  @Override
  public void onShowPress(MotionEvent e) {
   // TODO Auto-generated method stub
   super.onShowPress(e);
  }

  @Override
  public boolean onSingleTapConfirmed(MotionEvent e) {
   // TODO Auto-generated method stub
   Log.e("onSingleTapConfirmed+play()", "---------");
   if(isPaused==false||isStopped==true){
   prepareMedia(MainActivity.this.songpath);
   }
   else{
    playMedia();
   }
   return true;
  }

  @Override
  public boolean onSingleTapUp(MotionEvent e) {
   // TODO Auto-generated method stub
   return true;
  }

 }

 @Override
 public boolean onTouch(View v, MotionEvent event) {
  // TODO Auto-generated method stub
  if (songList.size() > 0) {
   return detector.onTouchEvent(event);
  }
  return false;
 }

 // 选择播放类型
 class SongFilter implements FilenameFilter {

  @Override
  public boolean accept(File arg0, String arg1) {
   // TODO Auto-generated method stub
   if (arg1.endsWith(".wmv")) {
    return true;
   } else if (arg1.endsWith(".mp3")) {
    return true;
   }
   return false;
  }

 }

 // 获得歌曲列表
 public void songList() {

  File rootPath = new File(getPath());
  Log.e("PATH-----", rootPath.getPath());
  // 如果存在.mp3 wmv歌曲
  if (rootPath.listFiles(new SongFilter()).length > 0) {
   for (File file : rootPath.listFiles(new SongFilter())) {
    MainActivity.this.songList.add(file.getName());
   }
   addBtnListener();
  } else {
   Toast.makeText(this, "未找到歌曲", 2000).show();
   removeBtnListener();
  }
 }
    //增加按钮监听
 private void addBtnListener(){
  stopBtn.setOnClickListener(new ImaBtnClickListener());
  cycleBtn.setOnClickListener(new ImaBtnClickListener());
  randomBtn.setOnClickListener(new ImaBtnClickListener());
  playBtn.setOnClickListener(new ImaBtnClickListener());
  pauseBtn.setOnClickListener(new ImaBtnClickListener());
  nextSongBtn.setOnClickListener(new ImaBtnClickListener());
  lastSongBtn.setOnClickListener(new ImaBtnClickListener());
 }
 
 //移除按钮监听
 private void removeBtnListener(){
  stopBtn.setOnClickListener(null);
  cycleBtn.setOnClickListener(null);
  randomBtn.setOnClickListener(null);
  playBtn.setOnClickListener(null);
  pauseBtn.setOnClickListener(null);
  nextSongBtn.setOnClickListener(null);
  lastSongBtn.setOnClickListener(null);
 }
 class ImaBtnClickListener implements OnClickListener {

  @Override
  public void onClick(View v) {
   // TODO Auto-generated method stub
   switch (v.getId()) {
   case R.id.playBtn:
    Log.e("playListener", "--------------");
    // 如果记录存在,则当前歌曲为上一次已完成歌曲的下一首
    if(isPaused==false||isStopped==true){
    prepareMedia(songpath);
    }else{
     playMedia();
    }
    break;
   case R.id.pauseBtn:
    Log.e("pauseListener", "-------");
    pauseMeida();
    break;
   case R.id.nextSongBtn:
    Log.e("nextSongListener", "--------------");
    nextSong();
    break;
   case R.id.lastSongBtn:
    Log.e("lastSongListener", "--------------");
    lastSong();
    break;
   case R.id.voicMaxBtn:
    voiceManagerMax();
    break;
   case R.id.voiceMinBtn:
    voiceManagerMin();
    break;
   case R.id.voiceDefaultBtn:
    voiceManagerDefault();
    break;
   case R.id.stopBtn:
    stopPlayer();
    break;
   case R.id.cycleBtn:
    recyleCurrentSong();
    break;
   case R.id.randomBtn:
    randomPlay();
    break;
   case R.id.pathBtn:
    // getRootPath();
    createDialog();
   }
  }

 }

 // 暂停
 private void pauseMeida() {
  Log.e("In pauseMedia()", "-----");
  isPaused=true;
  if (mediaPlayer.isPlaying()) {
   mediaPlayer.pause();
   songNamText.setText(songList.get(currentSong) + "---暂停中");
  }
 }
 
 //播放器准备
 private void prepareMedia(String songPath){
  Log.e("SONGPATH", songPath);
  isStopped=false;
  if (MainActivity.this.currentSong >= songList.size()) {
   MainActivity.this.currentSong = 0;
  }
  mediaPlayer.reset(); 
   try {
    File songFile=new File(songPath);
    FileInputStream fis=new FileInputStream(songFile);
    mediaPlayer.setDataSource(fis.getFD());
    mediaPlayer.prepare();
   }catch(Exception e){
    e.printStackTrace();
   }
   playMedia();
 }

 // 播放
 private void playMedia() {
  if (!mediaPlayer.isPlaying()) {
   if (MainActivity.this.currentSong >=songList.size()) {
    MainActivity.this.currentSong = 0;
   }
     
    mediaPlayer.start();
    isPaused=false;
    Log.e("In playMedia()", "-----");
    mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

     @Override
     public void onCompletion(MediaPlayer mp) {
      // TODO Auto-generated method stub
      if (MainActivity.this.id == 1) {// 单曲循环
       prepareMedia(MainActivity.this.songpath);
       strogeMusicSP(currentSong);
      } else if (MainActivity.this.id == -1) {// 顺序播放(默认模式)
       nextSong();
       strogeMusicSP(currentSong);
      } else if (MainActivity.this.id == 0) {// 随机播放
       currentSong = (int) (songList.size() * Math
         .random()) + 1;
       MainActivity.this.songpath = songRootPath
         +"/"+ songList.get(currentSong);
       prepareMedia(MainActivity.this.songpath);
       strogeMusicSP(currentSong);
      }
     }
    });
    if(mediaPlayer.isPlaying()){
     Log.e("IsPlaying()", "-----------");
    }
   if (MainActivity.this.id == 1) {
    songNamText.setText(songList.get(currentSong)
      + "---播放中--单曲循环模式");
   } else if (MainActivity.this.id == 0) {
    songNamText.setText(songList.get(currentSong)
      + "---播放中--随机播放模式");
   } else {
    songNamText.setText(songList.get(currentSong) + "---播放中--顺序播放模式");
   }
  }
 }

 // 下一首
 private void nextSong() {
  Log.e("In nextSong()", "------");
  if (MainActivity.this.currentSong >= (songList.size() - 1)) {
   MainActivity.this.currentSong = 0;
  } else {
   MainActivity.this.currentSong++;
  }
  MainActivity.this.songpath = songRootPath + "/"+songList.get(currentSong);
  if (mediaPlayer.isPlaying()) {
   prepareMedia(MainActivity.this.songpath);
  }else if(isStopped==true){
   songNamText.setText(songList.get(currentSong) + "---停止中");
  }else{
   songNamText.setText(songList.get(currentSong) + "---暂停中");
  }
 }

 // 停止
 private void stopPlayer() {
  mediaPlayer.stop();
  isStopped=true;
  songNamText.setText(songList.get(currentSong) + "---停止中");
 }

 // 上一首
 private void lastSong() {
  Log.e("In LastSong()", "------");
  if ((MainActivity.this.currentSong - 1) < 0) {
   MainActivity.this.currentSong = songList.size() - 1;
  } else {
   MainActivity.this.currentSong--;
  }
  MainActivity.this.songpath = songRootPath + "/"+songList.get(currentSong);
  if (mediaPlayer.isPlaying()) {
   
   prepareMedia(MainActivity.this.songpath);
  } else if(isStopped==true){
   songNamText.setText(songList.get(currentSong) + "---停止中");
  }else{
   songNamText.setText(songList.get(currentSong) + "---暂停中");
  }
 }

 // 一次单曲循环,一次单击取消转顺序
 private void recyleCurrentSong() {
  Log.e("In recyleCurrentSong()", "------");
  if (MainActivity.this.id != 1) {
   MainActivity.this.id = 1;
   MainActivity.this.songpath = songRootPath
     + "/"+songList.get(currentSong);
   songNamText.setText(songList.get(currentSong) + "---播放中--单曲循环模式");
  } else {
   MainActivity.this.id = -1;
   getSongCount();
   songNamText.setText(songList.get(currentSong) + "---播放中");
  }
 }

 // 一次随机播放,一次单击取消转顺序
 private void randomPlay() {
  Log.e("In randomPlay()", "------");
  if (MainActivity.this.id != 0) {
   MainActivity.this.id = 0;
   songNamText.setText(songList.get(currentSong) + "---播放中--随机播放模式");
  } else {
   MainActivity.this.id = -1;
   getSongCount();
   songNamText.setText(songList.get(currentSong) + "---播放中");
  }
 }

 // 降低音量
 private void voiceManagerMin() {
  MainActivity.this.audioManager.adjustStreamVolume(
    AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER,
    AudioManager.FLAG_SHOW_UI);
 }

 // 提高音量
 private void voiceManagerMax() {
  MainActivity.this.audioManager.adjustStreamVolume(
    AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE,
    AudioManager.FLAG_SHOW_UI);
 }

 // 静音
 private void voiceManagerDefault() {
  MainActivity.this.audioManager.setStreamVolume(
    AudioManager.STREAM_MUSIC, 0, AudioManager.FLAG_SHOW_UI);
 }

 // 存储播放器歌曲记录
 private void strogeMusicSP(int currentSong) {
  Context ctx = MainActivity.this;
  SharedPreferences sp = ctx.getSharedPreferences("SP", MODE_PRIVATE);
  Editor editor = sp.edit();
  editor.putInt("SimpleMedia_int_currentSong", currentSong);
  editor.commit();
 }

 // 存储播放器路径记录
 private void strogePathSP(String songRootPath) {
  Context ctx = MainActivity.this;
  SharedPreferences sp = ctx.getSharedPreferences("SP", MODE_PRIVATE);
  Editor editor = sp.edit();
  editor.putString("SimpleMedia_string_currentPath", songRootPath);
  editor.commit();
 }

 // 获取播放器记录中上次歌曲位置
 private void getSongCount() {
  Context ctx = MainActivity.this;
  SharedPreferences sp = ctx.getSharedPreferences("SP", MODE_PRIVATE);
  songCount = sp.getInt("SimpleMedia_int_currentSong", -1);
  if (songCount != -1) {
   MainActivity.this.currentSong = songCount;
  }
  if ((songList.size() > 0) ) {
   // 获取播放歌曲的路径
   if(MainActivity.this.currentSong>=songList.size()){
    MainActivity.this.currentSong=0;
   }
   MainActivity.this.songpath = MainActivity.this.songRootPath +"/"+songList.get(currentSong);
  }
 }

 // 获取播放器记录中上次播放的路径
 private String getPath() {
  Context ctx = MainActivity.this;
  SharedPreferences sp = ctx.getSharedPreferences("SP", MODE_PRIVATE);
  path = sp.getString("SimpleMedia_string_currentPath", null);
  if (path != null) {
   Log.e("in getPath()",path);
   MainActivity.this.songRootPath = path;
   return MainActivity.this.songRootPath;
  } else {
   MainActivity.this.songRootPath="/mnt/sdcard/";
   return songRootPath;
  }
 }

 // 播放器路径选择
 private void getRootPath() {
  Log.e("LISTVIEW", "----");
  File root = new File(rootPath);
  if (root.exists()) {
   currentParent = root;
   currentFiles = root.listFiles();// 获取根目录下所有文件
   createListView(currentFiles);
  }
  showPathList.setOnItemClickListener(new OnItemClickListener() {

   @Override
   public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
     long arg3) {
    // TODO Auto-generated method stub
    if (arg2 == 0) {
     try {
      if (currentParent.getParentFile().getPath().equals(
        "/mnt")){
       
      }else {
       currentParent = currentParent.getParentFile();
       currentFiles = currentParent.listFiles();
       MainActivity.this.currentRootPath = currentFiles[arg2].getParentFile().getPath();
       createListView(currentFiles);
      }
     } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    } else {
     File[] childFiles = currentFiles[arg2 - 1].listFiles();
     MainActivity.this.currentRootPath = currentFiles[arg2 - 1].getPath();
     if (childFiles != null && childFiles.length > 0) {
      currentParent = currentFiles[arg2 - 1];
      currentFiles = childFiles;
      MainActivity.this.createListView(currentFiles);
     } else {
      Toast.makeText(getApplicationContext(), "文件为空或不可访问",
        2000);
     }
    }
   }
  });

 }

 // listview显示目录
 private void createListView(File[] currentFiles) {
  List<String> fileNameList = new ArrayList<String>();
  showPathText.setText(currentRootPath);
  fileNameList.add("返回上一级");
  for (int i = 0; i < currentFiles.length; i++) {
   fileNameList.add(currentFiles[i].getName());
  }
  showPathList.setAdapter(new ArrayAdapter<String>(MainActivity.this,
    android.R.layout.simple_expandable_list_item_1, fileNameList));
  //setContentView(showPathList);
 }
  //创建dialog
 private void createDialog() {
  Builder builder=new AlertDialog.Builder(this);
  LinearLayout pathLayout=(LinearLayout) getLayoutInflater().inflate(R.layout.path_select, null);
  showPathList = (ListView) pathLayout.findViewById(R.id.showPathList);
  showPathText = (TextView) pathLayout.findViewById(R.id.showPathText);
  getRootPath();//获取路径
  
  builder.setView(pathLayout);
  builder.setPositiveButton("确认路径",
    new DialogInterface.OnClickListener() {

     @Override
     public void onClick(DialogInterface dialog, int which) {
      // TODO Auto-generated method stub
      Log.e("CurrentRootPath", MainActivity.this.currentRootPath);
      strogePathSP(MainActivity.this.currentRootPath);
      songList();
      Log.e("CreateDialog-songList()", "---------------");
      getSongCount();
     }
    });
  builder.setNegativeButton("取消选择",
    new DialogInterface.OnClickListener() {
   
     @Override
     public void onClick(DialogInterface dialog, int which) {
      // TODO Auto-generated method stub
      currentRootPath="/mnt/sdcard/";
     }
    });
        builder.create().show();
 }
  //长按返回键退出
 @Override
 public boolean onKeyLongPress(int keyCode, KeyEvent event) {
  // TODO Auto-generated method stub
  if(keyCode==KeyEvent.KEYCODE_BACK){
   System.exit(0);
  }
  return super.onKeyLongPress(keyCode, event);
 }

   
     
}

猜你喜欢

转载自yypdc.iteye.com/blog/2002430