nameTextView 用来显示播放mp3 音乐名称
seekBar 拖动条-进度条
listView 存放搜索出来的MP3音乐列表
List<File> list 存放:MP3文件集合
List<Map<String,String>> data :存放Map<String,String> map :键值对信息map<name,path>
SimpleAdapter 适配器 給listView.setAdapter(adapter);
listView 设置监听-通过点击哪个music item :position 播放音乐
listView.setOnItemClickListener(new MyItemListener());
paly(){
通过全局变量current
player.setDataSource(data.get(current).get("path")); //获取歌曲路径
nameTextView.setText(data.get(current).get("name")); //在mTextView-显示歌名
seekBar.setMax(player.getDuration()); //显示seekBar长度 -设置进度条长度
}
activity.java
package com.example.musicplayer;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
/**
* nameTextView :显示播放音乐的名称
* seekBar : 音乐播放进度条
* listView : 音乐list 列表
* ppButton : 播放按钮
* current :点击 音乐 列表 获取点击的item : position
* SimpleAdapter (Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)
* List<Map<String,String>> data;
* @author Administrator
*
*/
public class MainActivity extends Activity {
private TextView nameTextView;
private SeekBar seekBar;
private ListView listView;
private List<Map<String,String>> data;
private int current;
private MediaPlayer player;
private Button ppButton,previousBut,nextBut;
private boolean isPause;
private boolean isStartTrackingTouch;
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
nameTextView = (TextView) findViewById(R.id.name);
seekBar = (SeekBar) findViewById(R.id.seekBar);
listView = (ListView) findViewById(R.id.list);
ppButton = (Button) findViewById(R.id.pp);
previousBut = (Button) findViewById(R.id.previous);
nextBut = (Button) findViewById(R.id.next);
ppButton.setOnClickListener(new MyButListener());
previousBut.setOnClickListener(new MyButListener());
nextBut.setOnClickListener(new MyButListener());
//1.create 创建音乐播放器
player = new MediaPlayer();
//2.显示音乐播放列表-内部方法generateListView();
generateListView();
//3.进度条 seekBar监听
seekBar.setOnSeekBarChangeListener(new MySeekBarListener());
//4.播放器监听器
player.setOnCompletionListener(new MyPlayerListener());
//5.intent filter 意图过滤器
IntentFilter filter = new IntentFilter();
//6.播出电话暂停音乐
filter.addAction("android.intent.action.NEW_OUTGOING_CALL");
registerReceiver(new PhoneListener(), filter);
//7.1创建电话服务
TelephonyManager manager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
//7.2监听电话状态,接电话时停止播放
manager.listen(new MyPhoneStateListener(), PhoneStateListener.LISTEN_CALL_STATE);
}
/**
* 7.2 监听电话状态
* @author Administrator
*
*/
private class MyPhoneStateListener extends PhoneStateListener{
@Override
public void onCallStateChanged(int state, String incomingNumber) {
pause();
}
}
/**
* 播放器监听器
* @author Administrator
*
*/
private class MyPlayerListener implements OnCompletionListener{
@Override
public void onCompletion(MediaPlayer mp) {
next();
}
}
/**
* 播放先一首歌
*/
private void next() {
current = (current+1) % data.size();
play();
}
/**
* 播放前一首歌
*/
private void previous() {
current = current-1 < 0 ? data.size()-1 : current-1;
play();
}
/**
* 此类是进度条监听器
* @author Administrator
*
*/
public class MySeekBarListener implements OnSeekBarChangeListener {
//移动触发
@Override
public void onProgressChanged(SeekBar seekBer, int progress, boolean fromUser) {
}
//起始位置触发
@Override
public void onStartTrackingTouch(SeekBar seekBer) {
isStartTrackingTouch = true;
}
//结束触发
@Override
public void onStopTrackingTouch(SeekBar seekBer) {
player.seekTo(seekBar.getProgress());
isStartTrackingTouch = false;
}
}
/**
* 2.显示音乐播放列表-内部方法generateListView();
*/
private void generateListView() {
//list 文件列表
List<File> list = new ArrayList<File>();
//2.1获取sdcard 中的所有歌曲
findAll(Environment.getExternalStorageDirectory(),list);
//2.2 播放列表进行排序,字符顺序排序
Collections.sort(list);
//3.遍历list<File> 存放的.mp3 file 集合
data = new ArrayList<Map<String,String>>();
for(File file : list){
Map<String,String> map = new HashMap<String, String>();
map.put("name", file.getName());
map.put("path", file.getAbsolutePath());
data.add(map);
}
//4.SimpleAdapter (Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)
SimpleAdapter adapter = new SimpleAdapter(
this,
data,
R.layout.item,
new String[]{"name"},
new int[]{R.id.mName});
listView.setAdapter(adapter);
listView.setOnItemClickListener(new MyItemListener());
}
/**
* list view 音乐列表点击事件:position
* 点击的哪个音乐 item:初入 position
* @author Administrator
*
*/
class MyItemListener implements OnItemClickListener{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
current = position;
play();
}
}
/**
* 2.1
* 查找文件路径中所有mp3文件
* file.listFiles();是获取file这个对象也就是file这个目录下面的文件和文件夹的集合
* for(File subFile : subFiles){}就是循环遍历list中存放的数据
*
* @param file 要找的目录
* @param list 用来装.mp3文件的List<File>集合
*/
private void findAll(File file, List<File> list) {
File[] subFiles = file.listFiles();
if(subFiles != null){
for(File subFile : subFiles){
if(subFile.isFile() && subFile.getName().endsWith(".mp3"))
list.add(subFile); //list 集合添加.MP3 结尾文件
else if(subFile.isDirectory())//如果是目录
findAll(subFile, list);//递归循环
}
}
}
/**
* 按钮监听
* @author Administrator
*
*/
class MyButListener implements OnClickListener{
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.pp:
//播放/暂停按钮-默认从第一首歌曲开始播放
if(!player.isPlaying() && !isPause){
play();
}
Button but = (Button) view ;
//播放/暂停 按钮变化
if("||".equals(but.getText())){
pause();
but.setText("▶");
}else{
resume();
but.setText("||");
}
break;
case R.id.next:
next();
break;
case R.id.previous:
previous();
break;
default:
break;
}
}
}
/**
* 从新开始功能实现
*/
private void resume() {
if(isPause){
player.start();
isPause = false;
}
}
/**
* 暂停功能实现
*/
private void pause() {
if(player != null && player.isPlaying()){
player.pause();
isPause = true;
}
}
/**
* 接收 广播 时暂停播放
* @author Administrator
*
*/
private class PhoneListener extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
pause();
}
}
/**
* 恢复播放
* @see android.app.Activity#onResume()
*/
@Override
protected void onResume() {
super.onResume();
resume();
}
/**
* current:list item 显示的歌曲名称
* 通过点击事件,获取current 下标,获取本下标对应的歌曲属性 path name
* 播放
*/
private void play() {
try {
//重播
player.reset();
//获取歌曲路径
player.setDataSource(data.get(current).get("path"));
//在mTextView-显示歌名
nameTextView.setText(data.get(current).get("name"));
//准备-缓冲
player.prepare();
//开始播放
player.start();
//显示seekBar长度 -设置进度条长度
seekBar.setMax(player.getDuration());
//播放按钮样式
ppButton.setText("||");
//发送一个Runnable, handler收到之后就会执行run()方法
handler.post(new Runnable() {
@Override
public void run() {
// 更新进度条
if(!isStartTrackingTouch)
seekBar.setProgress(player.getCurrentPosition());
//1 秒后再次发送
handler.postDelayed(this, 100);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<SeekBar
android:id="@+id/seekBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp" />
<LinearLayout
android:gravity="center_horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp" >
<Button
android:id="@+id/previous"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:text="|◀"
android:onClick="previous"/>
<Button
android:id="@+id/pp"
android:layout_width="40dp"
android:layout_height="40dp"
android:text="▶" />
<Button
android:id="@+id/next"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:text="▶|"
android:onClick="next"/>
</LinearLayout>
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
item.xml 用来显示listView 列表的
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:padding="10dp" >
<TextView
android:id="@+id/mName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="15sp"
/>
</LinearLayout>
参考文章:http://www.linuxidc.com/Linux/2011-10/44420.htm