使用MediaPlayer+Service完成音乐播放器
1,先把歌曲封装成一个类
package com.example.servicemusic;
public class Song {
private String title;
private String artist;
private int duration;
private String data;
private int size;
public Song(String title, String artist, int duration, String data, int size) {
this.title = title;
this.artist = artist;
this.duration = duration;
this.data = data;
this.size = size;
}
public Song() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
}
2,封装查询本地歌曲的工具类
package com.example.servicemusic;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import java.util.ArrayList;
import java.util.List;
public class Utils {
private Context context;
private List<Song> list;
public Utils(Context context, List<Song> list) {
this.context = context;
this.list = list;
}
public static List<Song> init(Context context){
List<Song> list=new ArrayList<>();
//获取音乐的uri
Uri uri= MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String[] strings={MediaStore.Audio.Media.TITLE,MediaStore.Audio.Media.ARTIST,MediaStore.Audio.Media.DURATION,MediaStore.Audio.Media.DATA,MediaStore.Audio.Media.SIZE};
ContentResolver contentResolver = context.getContentResolver();
Cursor cursor = contentResolver.query(uri, strings, null, null, null);
while (cursor.moveToNext()){
//获取音乐的歌名,作者,时长,地址
String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
int duration = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
int size = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.SIZE));