Android開發Mp3播放器工具類
最近專案在用到Mp3播放器直接播放音樂,於是整理一個播放器工具類,記錄下.以便日後使用.
①首先把使用到的MP3內容封裝成的類列出來
/**
* map3內容
*/
public class Mp3 {
public int id;
public int playlistId;//列表id
public String albumName;//專輯名字
public String singerName;//歌手名字
public String url;//sd卡路徑
public String name;//歌曲名字
public int pictureID;
public int Duration;
private long allSongIndex ;
public String picUrl;//圖片路徑
public int getSqlId() {
return id;
}
public void setSqlId(int sqlId) {
this.id = sqlId;
}
public int getPlaylistId() {
return playlistId;
}
public void setPlaylistId(int playlistId) {
this.playlistId = playlistId;
}
public int getDuration() {
return Duration;
}
public void setDuration(int duration) {
Duration = duration;
}
public String getAlbumName() {
return albumName;
}
public String getSingerName () {
return singerName;
}
public void setAlbumName(String albumName) {
this.albumName = albumName;
}
public void setSingerName(String singerName) {
this.singerName = singerName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getName() {
return name;
}
public int getPictureID() {
return pictureID;
}
public void setPictureID(int pictureID) {
this.pictureID = pictureID;
}
public void setName(String name) {
this.name = name;
}
public long getAllSongIndex() {
return allSongIndex;
}
public void setAllSongIndex(long allSongIndex) {
this.allSongIndex = allSongIndex;
}
@Override
public String toString() {
return "Mp3 [id=" + id + ", playlistId=" + playlistId + ", albumName="
+ albumName + ", singerName=" + singerName + ", url=" + url
+ ", name=" + name + ", pictureID=" + pictureID + ", Duration="
+ Duration + ", allSongIndex=" + allSongIndex + "]";
}
public String getPicUrl() {
return picUrl;
}
public void setPicUrl(String picUrl) {
this.picUrl = picUrl;
}
}
/**
* 專輯類
*/
public class Album {
public String name;
public String singerName;
public Bitmap picture;
public String getSingerName() {
return singerName;
}
public void setSingerName(String singerName) {
this.singerName = singerName;
}
public String getName() {
return name;
}
public Bitmap getPicture() {
return picture;
}
public void setName(String name) {
this.name = name;
}
public void setPicture(Bitmap picture) {
this.picture = picture;
}
}
/**
* 記憶體卡快取類
*/
public class MemoryCache {
private static final String TAG = "MemoryCache";
private Map<String, Bitmap> cache = Collections
.synchronizedMap(new LinkedHashMap<String, Bitmap>(10, 1.5f, true));
private long size = 0;// current allocated size
private long limit = 1000000;// max memory in bytes
public MemoryCache() {
// use 25% of available heap size
setLimit(Runtime.getRuntime().maxMemory() / 10);
}
public void setLimit(long new_limit) {
limit = new_limit;
Log.i(TAG, "MemoryCache will use up to " + limit / 1024. / 1024. + "MB");
}
public Bitmap get(String id) {
try {
if (!cache.containsKey(id))
return null;
return cache.get(id);
} catch (NullPointerException ex) {
return null;
}
}
public void put(String id, Bitmap bitmap) {
try {
if (cache.containsKey(id))
size -= getSizeInBytes(cache.get(id));
cache.put(id, bitmap);
size += getSizeInBytes(bitmap);
checkSize();
} catch (Throwable th) {
th.printStackTrace();
}
}
private void checkSize() {
Log.i(TAG, "cache size=" + size + " length=" + cache.size());
if (size > limit) {
// 先遍歷最近最少使用的元素
Iterator<Entry<String, Bitmap>> iter = cache.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, Bitmap> entry = iter.next();
size -= getSizeInBytes(entry.getValue());
iter.remove();
if (size <= limit)
break;
}
Log.i(TAG, "Clean cache. New size " + cache.size());
}
}
public void clear() {
cache.clear();
}
/**
* 圖片佔用的記憶體
*
*/
long getSizeInBytes(Bitmap bitmap) {
if (bitmap == null)
return 0;
return bitmap.getRowBytes() * bitmap.getHeight();
}
}
/**
* 圖片載入
*/
public class ImageLoader {
private Context context; // 執行上下文
private MemoryCache memoryCache = new MemoryCache();
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
// 執行緒池
private ExecutorService executorService;
public ImageLoader(Context context) {
executorService = Executors.newFixedThreadPool(5);
this.context = context;
}
// 最主要的方法
public void DisplayImage(String url, ImageView imageView, boolean isLoadOnlyFromCache) {
imageViews.put(imageView, url);
// 先從記憶體快取中查詢
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else if (!isLoadOnlyFromCache){
Log.v("image", "1");
// 若沒有的話則開啟新執行緒載入圖片
queuePhoto(url, imageView);
}
}
private void queuePhoto(String url, ImageView imageView) {
PhotoToLoad p = new PhotoToLoad(url, imageView);
Log.v("image", "222"+url);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url) {
try {
Bitmap bitmap = null;
File file = new File(getAlbumArt(Integer.parseInt(url)));
bitmap = decodeFile(file);
return bitmap;
} catch (Exception ex) {
Log.e("image", "getBitmap catch Exception...\nmessage = " + ex.getMessage());
return null;
}
}
// decode這個圖片並且按比例縮放以減少記憶體消耗,虛擬機器對每張圖片的快取大小也是有限制的
private Bitmap decodeFile(File f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 100;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
return null;
}
// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad) {
this.photoToLoad = photoToLoad;
}
@Override
public void run() {
Bitmap bmp = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad))
return;
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
// 更新的操作放在UI執行緒中
Activity a = (Activity) photoToLoad.imageView.getContext();
a.runOnUiThread(bd);Log.v("image", "4");
}
}
/**
* 防止圖片錯位
*/
boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
if (tag == null || !tag.equals(photoToLoad.url))
return true;
return false;
}
// 用於在UI執行緒中更新介面
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
bitmap = b;
photoToLoad = p;
}
public void run() {
if (imageViewReused(photoToLoad))
return;
if (bitmap != null){
photoToLoad.imageView.setImageBitmap(bitmap);
Log.v("image", "5");
}
}
}
public String getAlbumArt(int trackId) {// trackId是音樂的id
String mUriTrack = "content://media/external/audio/media/#";
String[] projection = new String[] { "album_id" };
String selection = "_id = ?";
String[] selectionArgs = new String[] { Integer.toString(trackId) };
Cursor cur = context.getContentResolver().query(Uri.parse(mUriTrack), projection, selection, selectionArgs, null);
int album_id = 0;
if (cur.getCount() > 0 && cur.getColumnCount() > 0) {
cur.moveToNext();
album_id = cur.getInt(0);
}
cur.close();
cur = null;
if (album_id < 0) {
return null;
}
String mUriAlbums = "content://media/external/audio/albums";
projection = new String[] { "album_art" };
cur = context.getContentResolver().query(Uri.parse(mUriAlbums + "/" + Integer.toString(album_id)), projection, null, null, null);
String album_art = null;
if (cur.getCount() > 0 && cur.getColumnCount() > 0) {
cur.moveToNext();
album_art = cur.getString(0);
}
cur.close();
cur = null;
return album_art;
}
public void clearCache() {
memoryCache.clear();
}
}
②Mp3播放Util
public class MusicUtils {
private static List<String> mMusicList = new ArrayList<String>();
private static List<Album> albums = new ArrayList<Album>();
public static ArrayList<String> al_playlist = new ArrayList<String>();
private static List<Mp3> playList = new ArrayList<Mp3>();
private static String[] mCols = new String[]{MediaStore.Audio.Playlists._ID, MediaStore.Audio.Playlists.NAME};
/**
* 清空歌曲列表中的全部歌曲,plid為列表id
*/
public static void clearPlaylist(Context context, long plid) {
Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", plid);
context.getContentResolver().delete(uri, null, null);
return;
}
public static Cursor query(Context context, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
return query(context, uri, projection, selection, selectionArgs, sortOrder, 0);
}
public static Cursor query(Context context, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, int limit) {
try {
ContentResolver resolver = context.getContentResolver();
if (resolver == null) {
return null;
}
if (limit > 0) {
uri = uri.buildUpon().appendQueryParameter("limit", "" + limit).build();
}
return resolver.query(uri, projection, selection, selectionArgs, sortOrder);
} catch (UnsupportedOperationException ex) {
return null;
}
}
/**
* 得到歌曲列表中的全部歌曲,plid為列表id
*/
public static ArrayList<Mp3> getSongListForPlaylist(Context context, long plid) {
final String[] ccols = new String[]{MediaStore.Audio.Playlists.Members._ID, MediaStore.Audio.Playlists.Members.TITLE, MediaStore.Audio.Playlists.Members.ARTIST,
MediaStore.Audio.Playlists.Members.AUDIO_ID, MediaColumns.DATA};
Cursor cursor = query(context, MediaStore.Audio.Playlists.Members.getContentUri("external", plid), ccols, null, null, MediaStore.Audio.Playlists.Members.DEFAULT_SORT_ORDER);
if (cursor != null) {
ArrayList<Mp3> list = getSongListForCursor(context, cursor);
cursor.close();
return list;
}
return null;
}
public static ArrayList<Mp3> getSongListForCursor(Context context, Cursor cursor) {
if (cursor == null) {
return null;
}
int len = cursor.getCount();
long[] list = new long[len];
cursor.moveToFirst();
int id = -1, title = -1, artist = -1;
int allSongIndex = -1;
int url = -1;
try {
allSongIndex = cursor.getColumnIndexOrThrow(MediaStore.Audio.Playlists.Members.AUDIO_ID);
id = cursor.getColumnIndexOrThrow(MediaStore.Audio.Playlists.Members._ID);
title = cursor.getColumnIndexOrThrow(MediaStore.Audio.Playlists.Members.TITLE);
artist = cursor.getColumnIndexOrThrow(MediaStore.Audio.Playlists.Members.ARTIST);
url = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
} catch (IllegalArgumentException ex) {
id = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID);
}
ArrayList<Mp3> songs = new ArrayList<>();
songs.clear();
for (int i = 0; i < len; i++) {
long song_id = cursor.getLong(id);
long allSongId = cursor.getLong(allSongIndex);
String song_url = cursor.getString(url);
String tilte = cursor.getString(title);
String song_artist = cursor.getString(artist);
Mp3 song = new Mp3();
song.setSqlId(song_id + "");
song.setName(tilte);
song.setSingerName(song_artist);
song.setAllSongIndex(allSongId);
song.setUrl(song_url);
songs.add(song);
cursor.moveToNext();
}
return songs;
}
/**
* 將某一首歌新增到某個歌曲列表中,ids是歌曲id,playlistid是列表id
*/
public static void addToPlaylist(Context context, long[] ids, long playlistid) {
if (ids == null) {
Log.e("MusicBase", "ListSelection null");
} else {
int size = ids.length;
ContentResolver resolver = context.getContentResolver();
String[] cols = new String[]{"count(*)"};
Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistid);
Cursor cur = resolver.query(uri, cols, null, null, null);
cur.moveToFirst();
int base = cur.getInt(0);
cur.close();
int numinserted = 0;
for (int i = 0; i < size; i += 1000) {
makeInsertItems(ids, i, 1000, base);
numinserted += resolver.bulkInsert(uri, sContentValuesCache);
}
}
}
private static ContentValues[] sContentValuesCache = null;
private static void makeInsertItems(long[] ids, int offset, int len, int base) {
if (offset + len > ids.length) {
len = ids.length - offset;
}
if (sContentValuesCache == null || sContentValuesCache.length != len) {
sContentValuesCache = new ContentValues[len];
}
for (int i = 0; i < len; i++) {
if (sContentValuesCache[i] == null) {
sContentValuesCache[i] = new ContentValues();
}
sContentValuesCache[i].put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, base + offset + i);
sContentValuesCache[i].put(MediaStore.Audio.Playlists.Members.AUDIO_ID, ids[offset + i]);
}
}
/**
* 得到媒體庫中的全部歌曲名字
*/
public static List<String> getSongsName(Context context) {
Cursor c = query(context, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST, MediaColumns.DATA},
MediaStore.Audio.Media.IS_MUSIC + "=1", null, null);
try {
if (c == null || c.getCount() == 0) {
return null;
}
List<String> songsNameList = new ArrayList<>();
int columnIndexOrThrow = c.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
int len = c.getCount();
for (int i = 0; i < len; i++) {
c.moveToNext();
String song = c.getString(columnIndexOrThrow);
songsNameList.add(song);
}
return songsNameList;
} finally {
if (c != null) {
c.close();
}
}
}
/**
* 得到媒體庫中的全部歌曲
*/
public static ArrayList<Mp3> getAllSongs(Context context) {
Cursor c = query(context, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST, MediaColumns.DATA},
MediaStore.Audio.Media.IS_MUSIC + "=1", null, null);
try {
if (c == null || c.getCount() == 0) {
return null;
}
int len = c.getCount();
ArrayList<Mp3> list = new ArrayList<Mp3>();
int id = c.getColumnIndexOrThrow(MediaStore.Audio.Media._ID);
int title = c.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
int name = c.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST);
int url = c.getColumnIndex(MediaColumns.DATA);
for (int i = 0; i < len; i++) {
Mp3 mp3 = new Mp3();
c.moveToNext();
mp3.setSqlId(c.getLong(id) + "");
mp3.setName(c.getString(title));
mp3.setSingerName(c.getString(name));
mp3.setUrl(c.getString(url));
list.add(mp3);
}
return list;
} finally {
if (c != null) {
c.close();
}
}
}
/**
* 根據歌曲查詢歌曲
*/
public static ArrayList<Mp3> getSongByName(Context context, String searchName) {
Cursor c = query(context, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST, MediaColumns.DATA},
MediaStore.Audio.Media.IS_MUSIC + "=1", null, null);
try {
if (c == null || c.getCount() == 0) {
return null;
}
int len = c.getCount();
ArrayList<Mp3> list = new ArrayList<>();
int id = c.getColumnIndexOrThrow(MediaStore.Audio.Media._ID);
int title = c.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
int name = c.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST);
int url = c.getColumnIndex(MediaColumns.DATA);
for (int i = 0; i < len; i++) {
c.moveToNext();
String sName = c.getString(title);
if (sName.equals(searchName)) {
Mp3 mp3 = new Mp3();
mp3.setSqlId(c.getLong(id) + "");
mp3.setName(sName);
mp3.setSingerName(c.getString(name));
mp3.setUrl(c.getString(url));
list.add(mp3);
}
}
return list;
} finally {
if (c != null) {
c.close();
}
}
}
/**
* 得到所有歌手的名字列表
*/
public static List<String> MusicSingerList(Context context) {
mMusicList.clear();
if (mMusicList.size() == 0) {
ContentResolver cr = context.getContentResolver();
if (cr != null) {
// 獲取全部歌曲
Cursor cursor = cr.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
if (null == cursor) {
return null;
}
if (cursor.moveToFirst()) {
do {
String singer = cursor.getString(cursor.getColumnIndex(AudioColumns.ARTIST));
if ("<unknown>".equals(singer)) {
singer = "unknow artist";
}
String name = cursor.getString(cursor.getColumnIndex(MediaColumns.DISPLAY_NAME));
String sbr = name.substring(name.length() - 3, name.length());
// lac也是一種格式
if (sbr.equals("mp3") || sbr.endsWith("lac")) {
if (!mMusicList.contains(singer)) {
mMusicList.add(singer);
}
}
} while (cursor.moveToNext());
}
cursor.close();
}
}
return mMusicList;
}
/**
* 通過歌手名字,得到該歌手的所有歌曲
*/
public static ArrayList<Mp3> MusicMp3ListbySinger(Context context, String Name) {
ArrayList<Mp3> singerMp3 = new ArrayList<>();
if (singerMp3.size() == 0) {
ContentResolver cr = context.getContentResolver();
if (cr != null) {
// 獲取全部歌曲
Cursor cursor = cr.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
if (null == cursor) {
return null;
}
if (cursor.moveToFirst()) {
do {
String singer = cursor.getString(cursor.getColumnIndex(AudioColumns.ARTIST));
if ("<unknown>".equals(singer)) {
singer = "unknow artist";
}
if (singer.equals(Name)) {
int id = cursor.getInt(cursor.getColumnIndex(BaseColumns._ID));
int sid = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID);
String title = cursor.getString(cursor.getColumnIndex(MediaColumns.TITLE));
String url = cursor.getString(cursor.getColumnIndex(MediaColumns.DATA));
String name = cursor.getString(cursor.getColumnIndex(MediaColumns.DISPLAY_NAME));
String sbr = name.substring(name.length() - 3, name.length());
int duration = cursor.getInt(cursor.getColumnIndex(AudioColumns.DURATION));
long aLong = cursor.getLong(sid);
// Log.e("--------------", sbr);
if (sbr.equals("mp3") || sbr.endsWith("lac")) {
Mp3 mp3 = new Mp3();
mp3.setDuration(duration);
mp3.setName(title);
mp3.setPictureID(id);
mp3.setSingerName(singer);
mp3.setSqlId(aLong+"");
mp3.setUrl(url);
singerMp3.add(mp3);
}
}
} while (cursor.moveToNext());
}
cursor.close();
}
}
return singerMp3;
}
/**
* 得到所有專輯
*/
public static List<Album> MusicAlbumList(Context context) {
if (albums.size() == 0) {
ContentResolver cr = context.getContentResolver();
if (cr != null) {
// 獲取全部歌曲
Cursor cursor = cr.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
if (null == cursor) {
return null;
}
if (cursor.moveToFirst()) {
do {
String album = cursor.getString(cursor.getColumnIndex(AudioColumns.ALBUM));
if ("<unknown>".equals(album)) {
album = "unknow album";
}
String singer = cursor.getString(cursor.getColumnIndex(AudioColumns.ARTIST));
if ("<unknown>".equals(singer)) {
singer = "unknow artist";
}
String name = cursor.getString(cursor.getColumnIndex(MediaColumns.DISPLAY_NAME));
int id = cursor.getInt(cursor.getColumnIndex(BaseColumns._ID));
String sbr = name.substring(name.length() - 3, name.length());
if (sbr.equals("mp3") || sbr.endsWith("lac")) {
Album album2 = new Album();
album2.setSingerName(singer);
album2.setName(album);
album2.setPicture(BitmapFactory.decodeFile(getAlbumArt(context, id+"")));
if (!mMusicList.contains(album2.getName())) {
albums.add(album2);
mMusicList.add(album2.getName());
}
}
} while (cursor.moveToNext());
}
cursor.close();
}
}
return albums;
}
/**
* 通過歌曲id,找到其所對應的專輯圖片路徑
*/
public static String getAlbumArt(Context context, String trackId) {// trackId是音樂的id
String mUriTrack = "content://media/external/audio/media/#";
String[] projection = new String[]{"album_id"};
String selection = "_id = ?";
String[] selectionArgs = new String[]{trackId};
Cursor cur = context.getContentResolver().query(Uri.parse(mUriTrack),
projection, selection, selectionArgs, null);
int album_id = 0;
if (cur.getCount() > 0 && cur.getColumnCount() > 0) {
cur.moveToNext();
album_id = cur.getInt(0);
}
cur.close();
cur = null;
if (album_id < 0) {
return null;
}
String mUriAlbums = "content://media/external/audio/albums";
projection = new String[]{"album_art"};
cur = context.getContentResolver().query(Uri.parse(mUriAlbums + "/" +
Integer.toString(album_id)), projection, null, null, null);
String album_art = null;
if (cur.getCount() > 0 && cur.getColumnCount() > 0) {
cur.moveToNext();
album_art = cur.getString(0);
}
cur.close();
cur = null;
return album_art;
}
/**
* 得到專輯中的所有歌曲
*/
public static List<Mp3> MusicMp3ListbyAlbum(Context context, String Album) {
List<Mp3> albumMp3 = new ArrayList<Mp3>();
if (albumMp3.size() == 0) {
ContentResolver cr = context.getContentResolver();
if (cr != null) {
// 獲取全部歌曲
Cursor cursor = cr.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
if (null == cursor) {
return null;
}
if (cursor.moveToFirst()) {
do {
String album = cursor.getString(cursor.getColumnIndex(AudioColumns.ALBUM));
if ("<unknown>".equals(album)) {
album = "unknow album";
}
if (album.equals(Album)) {
String title = cursor.getString(cursor.getColumnIndex(MediaColumns.TITLE));
int id = cursor.getInt(cursor.getColumnIndex(BaseColumns._ID));
String url = cursor.getString(cursor.getColumnIndex(MediaColumns.DATA));
String name = cursor.getString(cursor.getColumnIndex(MediaColumns.DISPLAY_NAME));
String sbr = name.substring(name.length() - 3, name.length());
int duration = cursor.getInt(cursor.getColumnIndex(AudioColumns.DURATION));
// Log.e("--------------", sbr);
if (sbr.equals("mp3") || sbr.endsWith("lac")) {
Mp3 mp3 = new Mp3();
mp3.setDuration(duration);
mp3.setName(title);
mp3.setPictureID(id);
mp3.setUrl(url);
albumMp3.add(mp3);
}
}
} while (cursor.moveToNext());
}
cursor.close();
}
}
return albumMp3;
}
/**
* 得到所有歌曲列表的列表名字
*/
public static List<String> PlaylistList(Context context) {
List<String> listSongs = new ArrayList<String>();
if (listSongs.size() == 0) {
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, mCols, null, null, MediaStore.Audio.Playlists._ID + " desc");
al_playlist.clear();
int len = cursor.getCount();
int id = cursor.getColumnIndexOrThrow(MediaStore.Audio.Playlists._ID);
int name = cursor.getColumnIndexOrThrow(MediaStore.Audio.Playlists.NAME);
for (int i = 0; i < len; i++) {
cursor.moveToNext();
long id_temp = cursor.getLong(id);
String temp = cursor.getString(name);
al_playlist.add(id_temp + "");
listSongs.add(temp);
}
}
return listSongs;
}
/**
* 通過歌曲列表名找到列表id
*/
public static long getPlayListId(Context context, String listName) {
long listId = -1;
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, mCols, null, null, MediaStore.Audio.Playlists._ID + " desc");
al_playlist.clear();
int len = cursor.getCount();
int id = cursor.getColumnIndexOrThrow(MediaStore.Audio.Playlists._ID);
int name = cursor.getColumnIndexOrThrow(MediaStore.Audio.Playlists.NAME);
for (int i = 0; i < len; i++) {
cursor.moveToNext();
long id_temp = cursor.getLong(id);
String temp = cursor.getString(name);
if (listName.equals(temp)) {
listId = id_temp;
}
}
return listId;
}
public static List<Mp3> getPlayList() {
return playList;
}
public static void setPlayList(List<Mp3> playList) {
MusicUtils.playList = playList;
}
public static ArrayList<String> getAl_playlist() {
return al_playlist;
}
public static void setAl_playlist(ArrayList<String> al_playlist) {
MusicUtils.al_playlist = al_playlist;
}
}
③Mp3後臺播放Service
public class MusicPlayService extends Service {
private final IBinder mBinder = new LocalBinder();
private Context context;
private MediaPlayer mMediaPlayer = null;
private int currentTime = 0;//歌曲播放進度
private int currentListItme = -1;//當前播放第幾首歌
private List<Mp3> songs;//要播放的歌曲集合
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public void onCreate() {
super.onCreate();
if (mMediaPlayer==null){
mMediaPlayer = new MediaPlayer();
}
}
/**
*得到當前播放進度
*/
public int getCurent(){
if (mMediaPlayer.isPlaying()){
return mMediaPlayer.getCurrentPosition();
}else {
return currentTime;
}
}
/**
* 跳轉到播放的進度
*/
public void movePlay(int progress){
mMediaPlayer.seekTo(progress);
currentTime=progress;
}
/**
* 根據歌曲儲存路徑播放歌曲
*/
public void playMusic(String path) {
try {
/* 重置MediaPlayer */
mMediaPlayer.reset();
/* 設定要播放的檔案的路徑 */
mMediaPlayer.setDataSource(path);
mMediaPlayer.prepare();
/* 開始播放 */
mMediaPlayer.start();
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer arg0) {
// 播放完成一首之後進行下一首
nextMusic();
}
});
} catch (IOException e) {
}
}
/**
* 下一曲
*/
public void nextMusic() {
if (++currentListItme>=songs.size()){
currentListItme=0;
}
playMusic(songs.get(currentListItme).getUrl());
}
/**
* 上一曲
*/
public void preMusic(){
if (--currentListItme<0){
currentListItme=songs.size()-
相關推薦
Android開發Mp3播放器工具類
最近專案在用到Mp3播放器直接播放音樂,於是整理一個播放器工具類,記錄下.以便日後使用.
①首先把使用到的MP3內容封裝成的類列出來
/**
* map3內容
*/
public class Mp3 {
public int id;
Android開發 時間戳轉換工具類
package com.shangyi.common.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import ja
Android開發中常用的工具類
目前包括 HttpUtils、DownloadManagerPro、Safe.ijiami、ShellUtils、PackageUtils、PreferencesUtils、JSONUtils、FileUtils、ResourceUtils、StringUtils、Parc
android開發:播放音訊功能的工具類
播放音訊功能的工具類
/**
* 播放聲音工具類
* creator: ZZF
* careate date: 2018/5/25 10:36.
*/
public class Soun
安卓MP3播放器開發實例(3)之進度條和歌詞更新的實現
tac run detail datetime style mem poll() arc call
上一次談了音樂播放的實現,這次說下最復雜的進度條和歌詞更新。因為須要在播放的Activity和播放的Service間進行交互,所以就涉及了Activi
工業串口觸摸屏開發制作mp3播放器,單片機或PLC通過串口控制播放MP3音頻方法
百分比 通訊 觸摸 參與 blog 設備 並行 周期 運行 工業串口觸摸屏開發制作mp3播放器,單片機或PLC通過串口控制播放MP3音頻方法
在工業控制系統中將音樂或語音MP3的美和工控結合在一起,給人以賞心悅目的感受。隨著工業控制的發展,對工業控制的控制要求也越來越高,使
Android播放音訊工具類
播放完畢重置mediaplayer,播放完畢才能播放下一次。播放小音訊建議使用soundpool(音訊大小不超過900k)public class PlayMusicUtils {
privat
Android練習專案 Mp3播放器實現 歌詞同步播放(四)
其實到後面就需要我們如何顯示歌詞,對於歌詞的同步顯示還是比較好實現的,主要通過判斷當前播放的時間和每個結點的歌詞的時間的大小,來同步對應到結點的資料,現在就是如何來實現這個問題。
其實,這個時候就需要自定義控制元件來實現。
第一步需要自定義View的屬性。
ESP32 開發筆記(八)ESP32 MP3 播放器
ESP32 MP3 播放器
ESP32 MP3 播放器
開發環境
環境搭建
編譯執行
執行結果
ESP32 MP3 播放器
原始碼地址:GitHub
開發環境
開發框架:ESP-IDF、E
Android練習專案 Mp3播放器實現(一)
對於Android的學習,需要掌握的東西有點多,需要我們認真,小心,不斷的進取。前天突然有個想法,覺得Mp3播放器是一個可以練習的專案,於是在網上搜了下,發現有人已經寫了部落格,看了他們的部落格後,我覺得他們說的一點很對,Mp3播放器基本用到了Android裡面
Android全格式播放器開發(第五節ffplay android移植)
第五節ffplay android移植
工程地址:http://code.google.com/p/kudou-player/
--------------------------------------------
之前我們已經做了好了準備工作,現在還做ffplay
android版ape,flac,wav,mp3播放器
該播放器是根據網上一位大神的java swing版本的多音訊格式播放器修改的,這是他的播放器的下載地址,java swing版本:https://github.com/tulskiy/musique.git
這只是移植的一個demo,完成的功能如下:(沒相到java swing版本移植過來是這麼麻煩的)
目
Android視訊播放專案總結之 使用第三方Vitamio庫,開發萬能播放器(三)
前言
雖然Android已經內建了VideoView元件和MediaPlayer類來支援開發視訊播放器,但支援格式、效能等各方面都十分有限,這裡與大家一起利用開源專案Vitamio來打造屬於自
Android流媒體開發之路三:基於NDK開發Android平臺RTSP播放器
基於NDK開發Android平臺RTSP播放器
最近做了不少android端的開發,有推流、播放、直播、對講等各種應用,做了RTMP、RTSP、HTTP-FLV、自定義等各種協議,還是有不少收穫和心得的。我這邊做,核心模組和核心程式碼部分,都是基於NDK,用C++開發的,然後將so動態庫,在Android
android 獲取手機信息工具類
telephony == 系統 設備 android pack devices 信息 context
package com.yqy.yqy_listviewheadview;
import android.content.Context;
import androi
最全面的Java字節byte操作,處理Java基本數據的轉換及進制轉換操作工具,流媒體及java底層開發項目常用工具類
進制 string 常用工具類 cat i++ logs 指定位置 tput off 前言:用於處理Java基本數據的轉換及進制轉換操作工具
一、實現功能
1、int預byte互轉
2、int與byte[]互轉
3、short與byte互轉
4、short與byte[]互轉
android經常使用正則工具類
col 中文字符 post 身份證號碼 obi content 支持 return 空白
此類提供日常開發中經常使用的正則驗證函數。比方:郵箱、手機號、電話號碼、身份證號碼、日期、數字、小數、URL、IP地址等。使用Pattern對象的matches方法進行整個字符匹配
Android實現音樂播放器(一)
simple ani call ket 打開文件 界面 方式 .cn 點擊 Graphical User Interface
本篇文章記錄了我實現Android簡單音樂播放器的過程,(一)中介紹了怎麽構建音樂播放器的前端頁面。首先大家看一下,界面最後是這樣的(界面有
用arm-linux-gnueabihf移植MP3播放器libmad-0.15.1b的時候出現錯誤提示
移植 else /dev/null -- b- line .com ibm fail diff --git a/package/libmad/libmad-0.15.1b-thumb2-fixed-arm.patch b/package/libmad/libmad-0.15
web開發一些常用的工具類的網站
項目目錄 圖標 nbsp 菜鳥 rip icons power html css som 持續更新中..........
1. 網頁圖標網站:
http://fontawesome.io
下面的鏈接瀏覽其提供的圖標:
http://fontawesome.io/ico