1.建立音樂Bean類
private var id: String? = null
private var song: String? = null
private var singer: String? = null
private var album: String? = null
private var duration: String? = null
private var path: String? = null
private var albumUri: Uri ? = null ;
private var thumb:Bitmap? = null ;
2.權限配置
- 先在清單文件中加入
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
.安卓4.4後寫需要權限
- 6.0 後的動態權限申請,傳送門先不寫,這個文章自己還沒寫好
3.Layout設計
- Relativelayout,上面有個RecycleView
- 下面有個信息欄RelativeLayout
4. 獲取本地數據
- 使用了內容提供器,ContentProvider共享數據的好處是統一了數據訪問方式
- Cursor用法
fun loadLocalMusicDate(){
var resolver: ContentResolver =contentResolver
var uri:Uri=MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
val cursor: Cursor? = resolver.query(uri, null, null, null, null)
var id:Long=0
while(cursor!!.moveToNext()){
var song=cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE))
var singer=cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST))
var album=cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM))
id++
val sid = id.toString()
var albumId = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Albums.ALBUM_ID));
var path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA))
var duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION))
var sdf = SimpleDateFormat("mm:ss")
var time = sdf.format(Date(duration))
var albumUri:Uri ?=null
print("查找前uri "+albumUri+" albumID"+albumId )
albumUri= ContentUris.withAppendedId(Uri.parse("content://media/external/audio/albumart"), albumId)
println("查找後uri"+albumUri)
var thumb:Bitmap?=null
if (albumUri!=null)
{
thumb=createThumbFromUir(resolver,albumUri)
}else{
var res = getResources();
var bmp = BitmapFactory.decodeResource(res, R.drawable.icon_song);
thumb=bmp
}
val bean = LocalMusicBean(sid, song, singer, album, time, path,albumUri,thumb)
mDatas?.add(bean)
println("獲取數據成功:" + bean.toString())
}
cursor.close();
adapterT?.notifyDataSetChanged();
}
- 拿到專輯圖片路徑後,轉爲BMP
fun createThumbFromUir(res: ContentResolver, albumUri: Uri): Bitmap ?{
var inF: InputStream? = null
var bmp: Bitmap? = null
try {
inF = res.openInputStream(albumUri)
val sBitmapOptions = BitmapFactory.Options()
bmp = BitmapFactory.decodeStream(inF, null, sBitmapOptions)
inF!!.close()
} catch (e: FileNotFoundException) {
} catch (e: IOException) {
e.printStackTrace()
}
return bmp
}
- 其他的和Faraway,不贅述了,下次寫新的播放器再完善github