需求1:将内存卡中的MP3音乐读取出来并显示到列表当中
1. 从数据库中查询所有音乐数据,保存到List集合当中,List当中存放的是Mp3Info对象 2. 迭代List集合,把每一个Mp3Info对象的所有属性,保存到Map对象当中 3. 定义一个List集合,把Map对象添加到List集合当中 4. 通过定义一个SimpleAdpter,调用setAdpter方法,将数据显示到列表当中
- /**
- * 用于从数据库中查询歌曲的信息,保存在List当中
- *
- * @return
- */
- public List<Mp3Info> getMp3Infos() {
- Cursor cursor = getContentResolver().query(
- MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
- MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
- List<Mp3Info> mp3Infos = new ArrayList<Mp3Info>();
- for (int i = 0; i < cursor.getCount(); i++) {
- Mp3Info mp3Info = new Mp3Info();
- cursor.moveToNext();
- long id = cursor.getLong(cursor
- .getColumnIndex(MediaStore.Audio.Media._ID)); //音乐id
- String title = cursor.getString((cursor
- .getColumnIndex(MediaStore.Audio.Media.TITLE)));//音乐标题
- String artist = cursor.getString(cursor
- .getColumnIndex(MediaStore.Audio.Media.ARTIST));//艺术家
- long duration = cursor.getLong(cursor
- .getColumnIndex(MediaStore.Audio.Media.DURATION));//时长
- long size = cursor.getLong(cursor
- .getColumnIndex(MediaStore.Audio.Media.SIZE)); //文件大小
- String url = cursor.getString(cursor
- .getColumnIndex(MediaStore.Audio.Media.DATA)); //文件路径
- int isMusic = cursor.getInt(cursor
- .getColumnIndex(MediaStore.Audio.Media.IS_MUSIC));//是否为音乐
- if (isMusic != 0) { //只把音乐添加到集合当中
- mp3Info.setId(id);
- mp3Info.setTitle(title);
- mp3Info.setArtist(artist);
- mp3Info.setDuration(duration);
- mp3Info.setSize(size);
- mp3Info.setUrl(url);
- mp3Infos.add(mp3Info);
- }
- }
- return mp3Infos;
- }
- /**
- * 填充列表
- * @param mp3Infos
- */
- public void setListAdpter(List<Mp3Info> mp3Infos) {
- List<HashMap<String, String>> mp3list = new ArrayList<HashMap<String, String>>();
- for (Iterator iterator = mp3Infos.iterator(); iterator.hasNext();) {
- Mp3Info mp3Info = (Mp3Info) iterator.next();
- HashMap<String, String> map = new HashMap<String, String>();
- map.put("title", mp3Info.getTitle());
- map.put("Artist", mp3Info.getArtist());
- map.put("duration", String.valueOf(mp3Info.getDuration()));
- map.put("size", String.valueOf(mp3Info.getSize()));
- map.put("url", mp3Info.getUrl());
- mp3list.add(map);
- }
- mAdapter = new SimpleAdapter(this, mp3list,
- R.layout.music_list_item_layout, new String[] { "title", "Artist", "duration" },
- new int[] { R.id.music_title, R.id.music_Artist, R.id.music_duration });
- mMusiclist.setAdapter(mAdapter);
- }
实现效果如图:
需求2:点击列表的每一项,启动一个服务来播放音乐
1. 注册条目点击监听器OnItemClickListener
2. 定义一个实现OnItemClickListener接口的内部类
3. 定义一个继承Service的服务类PlayerServie
1. 注册条目点击监听器OnItemClickListener
- mMusiclist = (ListView) findViewById(R.id.music_list);
- mMusiclist.setOnItemClickListener(new MusicListItemClickListener());
- mp3Infos = getMp3Infos();
- setListAdpter(getMp3Infos());
2. 定义一个实现OnItemClickListener接口的内部类
- private class MusicListItemClickListener implements OnItemClickListener {
- @Override
- public void onItemClick(AdapterView<?> parent, View view, int position,
- long id) {
- if(mp3Infos != null) {
- Mp3Info mp3Info = mp3Infos.get(position);
- Log.d("mp3Info-->", mp3Info.toString());
- Intent intent = new Intent();
- intent.putExtra("url", mp3Info.getUrl());
- intent.putExtra("MSG", AppConstant.PlayerMsg.PLAY_MSG);
- intent.setClass(MainActivity.this, PlayerService.class);
- startService(intent); //启动服务
- }
- }
- }
3. 定义一个继承Service的服务类PlayerServie(未完善的Service类)
- package com.wwj.sb.service;
- import android.annotation.SuppressLint;
- import android.app.Service;
- import android.content.Intent;
- import android.media.MediaPlayer;
- import android.media.MediaPlayer.OnPreparedListener;
- import android.os.IBinder;
- import com.wwj.sb.domain.AppConstant;
- @SuppressLint("NewApi")
- public class PlayerService extends Service {
- private MediaPlayer mediaPlayer = new MediaPlayer(); //媒体播放器对象
- private String path; //音乐文件路径
- private boolean isPause; //暂停状态
- @Override
- public IBinder onBind(Intent arg0) {
- return null;
- }
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- if(mediaPlayer.isPlaying()) {
- stop();
- }
- path = intent.getStringExtra("url");
- int msg = intent.getIntExtra("MSG", 0);
- if(msg == AppConstant.PlayerMsg.PLAY_MSG) {
- play(0);
- } else if(msg == AppConstant.PlayerMsg.PAUSE_MSG) {
- pause();
- } else if(msg == AppConstant.PlayerMsg.STOP_MSG) {
- stop();
- }
- return super.onStartCommand(intent, flags, startId);
- }
- /**
- * 播放音乐
- * @param position
- */
- private void play(int position) {
- try {
- mediaPlayer.reset();//把各项参数恢复到初始状态
- mediaPlayer.setDataSource(path);
- mediaPlayer.prepare(); //进行缓冲
- mediaPlayer.setOnPreparedListener(new PreparedListener(position));//注册一个监听器
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 暂停音乐
- */
- private void pause() {
- if (mediaPlayer != null && mediaPlayer.isPlaying()) {
- mediaPlayer.pause();
- isPause = true;
- }
- }
- /**
- * 停止音乐
- */
- private void stop(){
- if(mediaPlayer != null) {
- mediaPlayer.stop();
- try {
- mediaPlayer.prepare(); // 在调用stop后如果需要再次通过start进行播放,需要之前调用prepare函数
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- @Override
- public void onDestroy() {
- if(mediaPlayer != null){
- mediaPlayer.stop();
- mediaPlayer.release();
- }
- }
- /**
- *
- * 实现一个OnPrepareLister接口,当音乐准备好的时候开始播放
- *
- */
- private final class PreparedListener implements OnPreparedListener {
- private int positon;
- public PreparedListener(int positon) {
- this.positon = positon;
- }
- @Override
- public void onPrepared(MediaPlayer mp) {
- mediaPlayer.start(); //开始播放
- if(positon > 0) { //如果音乐不是从头播放
- mediaPlayer.seekTo(positon);
- }
- }
- }
- }
public class MusicActivity extends Activity {
private boolean isStop = false;
private MediaPlayer mPlayer;
public final String TITLE = Environment.getExternalStorageDirectory()
+ "/iwantyourlove.mp3";
private File file;
private SeekBar seekBar;
private ImageView play;
private TextView title;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.music_main);
initWidgets();
}
// 重新初始化播放器
public void initWidgets() {
play = (ImageView) findViewById(R.id.img_stop);
title = (TextView) findViewById(R.id.title);
seekBar = (SeekBar) findViewById(R.id.seek);
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
//seekBar.setProgress(mPlayer.getCurrentPosition() *seekBar.getMax() / total);
//Log.i("sss", seekBar.getProgress()+"");
//mPlayer.seekTo(mPlayer.getCurrentPosition());
mPlayer.seekTo(seekBar.getProgress() * mPlayer.getDuration() /100 );
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// Log.i("progress", ""+progress);
// Log.i("qqq", seekBar.getProgress()+"");
// progress = currentPosition * 100 / duration;
//progress*duration/100
//mPlayer.seekTo(progress * mPlayer.getDuration() /100 );
}
});
file = new File(TITLE);
title.setText(file.getName());
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(TITLE);
mPlayer.prepare();
} catch (Exception e) {
e.printStackTrace();
}
}
public void play(View v) {
if (!mPlayer.isPlaying()) {
mPlayer.start();
}
}
public void pause(View v) {
if (mPlayer.isPlaying()) {
mPlayer.pause();
}
}
public void replay(View v) {
mPlayer.reset();
initWidgets();// 重新构建播放器
// mPlayer.start();
play(v);
}
public void stop(View v) {
isStop = true;
mPlayer.stop();
play.setImageResource(R.drawable.player_play);
}
// 用图片代替按钮
public void playOrPause(View v) {
if (isStop) {// 停止后重新开始播放
mPlayer.reset();
initWidgets();
mPlayer.start();
play.setImageResource(R.drawable.player_pause);
isStop = false;
} else if (mPlayer.isPlaying()) {// 播放状态
play.setImageResource(R.drawable.player_play);
mPlayer.pause();
} else {// 暂停状态
play.setImageResource(R.drawable.player_pause);
mPlayer.start();
}
// 异步任务
new MusicTask().execute();
}
@Override
protected void onDestroy() {
super.onDestroy();
// 释放资源
mPlayer.release();
}
// 音乐播放异步任务
class MusicTask extends AsyncTask<Void, Void, Void> {
//int current = mPlayer.getCurrentPosition();// 当前播放是什么位置,
int total = mPlayer.getDuration(); // 音乐总共多长时间
@Override
protected Void doInBackground(Void... params) {
// 让SeekBar跟着音乐一起向右边走
while (mPlayer.getCurrentPosition() <= total&&!isStop) { //!isPause不是停止状态
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress();
}
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
// Log.i("msg", ""+mPlayer.getCurrentPosition() * 100 / total);
seekBar.setProgress(mPlayer.getCurrentPosition() *seekBar.getMax() / total);
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
}