1、本应用主要实现了将手机中的音乐文件添加到显示列表中,可实现音乐的播放、暂停、上一首、下一首的基本功能。
2、代码下载地址:http://download.csdn.net/detail/u011324501/9494884
3、应用布局:main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/listView1"
android:listSelector="#fef"
android:drawSelectorOnTop="false"
android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</ListView>
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content" >
<SeekBar
android:id="@+id/seekBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="@+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="@string/next"
/>
<Button
android:id="@+id/pre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="@string/pre"
/>
<Button
android:id="@+id/pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="16dp"
android:layout_toRightOf="@+id/pre"
/>
<Button
android:id="@+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toLeftOf="@+id/next"
android:text="@string/stop"
/>
</RelativeLayout>
</LinearLayout>
</LinearLayout>
主代码实现:MainActivity.java
package com.example.music;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class MainActivity extends Activity {
private MediaPlayer mediaPlayer;
private List<String> audioList = new ArrayList<String>();
private LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
private int currentItem = 0;
private Button pause;
private SeekBar seekBar;
private Handler hd = new Handler();
private Runnable runnable = new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
int position = mediaPlayer.getCurrentPosition();//当前播播放位置
int total = mediaPlayer.getDuration();//
int progress = position *100 /total;
seekBar.setProgress(progress);
hd.postDelayed(this, 200);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mediaPlayer = new MediaPlayer();
Button next = (Button) findViewById(R.id.next);
pause = (Button) findViewById(R.id.pause);
Button pre = (Button) findViewById(R.id.pre);
Button stop = (Button) findViewById(R.id.stop);
/**
* next music
*/
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
nextMusic();
}
});
/**
* stop
*/
stop.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(mediaPlayer.isPlaying()){
mediaPlayer.stop();
}
pause.setText("播放");
}
});
//pause
pause.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
((Button)v).setText("播放");
}else{
mediaPlayer.start();
((Button)v).setText("暂停");
}
}
});
//nextMusic
next.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
nextMusic();
}
});
//preMusic
pre.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
preMusic();
}
});
/*************************************************************/
//通过getSystemService(Context.AUDIO_SERVICE)方法获得AudioManager实例对象。AudioManager就是我们定义的控制系统声音的对象。
final AudioManager am = (AudioManager) MainActivity.this.getSystemService(Context.AUDIO_SERVICE);
MainActivity.this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
seekBar = (SeekBar) findViewById(R.id.seekBar);
seekBar.setMax(100);//设置最大值为100
seekBar.setProgress(0);//设置初始值为0
//调节手机音量大小 默认音乐可取STREAM_VOICE_CALL(通话)、STREAM_SYSTEM(系统声音)、STREAM_RING(铃声)、STREAM_MUSIC(音乐)、STREAM_ALARM(闹铃声)
// seekBar.setMax(am.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
//final int progress = am.getStreamVolume(AudioManager.STREAM_MUSIC);
//seekBar.setProgress(progress);//进度条设置音量
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
//拖动滚动条设置当前播放的位置
int musicnow = mediaPlayer.getDuration();//音乐当前播放位置
mediaPlayer.seekTo(seekBar.getProgress() * musicnow/100);
mediaPlayer.start();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
hd.removeCallbacks(runnable);//启动线程,实时更新当前播放进度
hd.postDelayed(runnable,1000);
//am.setStreamVolume(AudioManager.STREAM_MUSIC, progress, AudioManager.FLAG_PLAY_SOUND);//
//mediaPlayer.seekTo(seekBar.getProgress());
}
});
/*************************************************************/
}
/**
* 加载歌曲
*/
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
new Thread(new Runnable() {
public void run() {
//audioList();
// 耗时的方法
handler.sendEmptyMessage(1);
// 执行耗时的方法之后发送消给handler
}
}).start();
}
Handler handler = new Handler() {
public void handleMessage(Message msg) {
// handler接收到消息后就会执行此方法
switch (msg.what) {
case 1:audioList();
break;
default:
break;
}
super.handleMessage(msg);
}
};
//下一首
protected void nextMusic() {
if(++currentItem >= audioList.size()){
currentItem = 0;
}
String path = map.get(audioList.get(currentItem));
playMusic(path);
}
//上一首
protected void preMusic() {
if(--currentItem >= 0){
if(currentItem >= audioList.size()){
currentItem = 0;
}
}else{
currentItem = audioList.size() - 1;
}
String path = map.get(audioList.get(currentItem));
playMusic(path);
}
/**
* 加载歌曲
*/
private void audioList() {
getFiles("/sdcard/");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,audioList);
ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> viewList, View view,
int position,long id) {
currentItem = position;
String path = map.get(audioList.get(position));
playMusic(path);
}
});
}
//播放音乐
protected void playMusic(String path) {
try {
if(mediaPlayer.isPlaying()){
mediaPlayer.stop();
}
mediaPlayer.reset();//重置
mediaPlayer.setDataSource(path);//指定要播放的音频文件
mediaPlayer.prepare();//预加载音频文件
mediaPlayer.start();
pause.setText("暂停");
pause.setEnabled(true);
hd.removeCallbacks(runnable);//启动线程,实时更新当前播放进度
hd.postDelayed(runnable,1000);
} catch (Exception e) {
e.printStackTrace();
}
}
//获取音乐文件路径
private void getFiles(String path) {
File files = new File(path);
File[] file = files.listFiles();
try {
for (File f : file) {
if(f.isDirectory()){
getFiles(f.getAbsolutePath());
}else{
if(f.length()>512)//设置获取音乐文件的大小
if(isAudioFile(f.getPath())){
audioList.add(f.getPath().substring(f.getPath().lastIndexOf("/")+1));
map.put(f.getPath().substring(f.getPath().lastIndexOf("/")+1), f.getPath());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static String[] imageFormatSet = new String[]{"mp3"};//设置获取音乐文件的格式
//private static String[] imageFormatSet = new String[]{"ape", "mp3", "wav" };
private boolean isAudioFile(String path) {
for(String format:imageFormatSet){
if(path.contains(format)){
return true;
}
}
return false;
}
}
</pre><pre>
用到权限:<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
实现的效果图: