android 使用MediaPlayer实现音乐播放--获取音乐数据

前面已经添加了权限,有权限后可以去数据库读取音乐文件,一般可以获取全部音乐、专辑、歌手、流派等。

  1. 获取全部音乐数据
java 复制代码
class MusicHelper {
    companion object {

        @SuppressLint("Range")
        fun getMusic(context: Context): MutableList<MusicData> {
            var songNumber = 0
            val songsList: MutableList<MusicData> = ArrayList() //用于装歌曲数据

            val contentResolver: ContentResolver = context.contentResolver
            var cursor: Cursor? = null
            try {
                cursor = contentResolver.query(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                    null, null, null, null
                );
                if (cursor != null) {
                    while (cursor.moveToNext()) {
                        //是否是音频
                        val isMusic =
                            cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.IS_MUSIC))
                        //时长
                        val duration =
                            cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION))
                        //是音乐并且时长大于30秒
                        if (isMusic != 0 && duration >= 30 * 1000) {
                            //歌名
                            val title = cursor.getString(
                                cursor.getColumnIndexOrThrow(
                                    MediaStore.Audio.Media.TITLE
                                )
                            )
                            //歌手
                            val artist = cursor.getString(
                                cursor.getColumnIndexOrThrow(
                                    MediaStore.Audio.Media.ARTIST
                                )
                            );
                            //专辑id
                            val albumId =
                                cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID))
                            //文件路径
                            val dataPath = cursor.getString(
                                cursor.getColumnIndexOrThrow(
                                    MediaStore.Audio.Media.DATA
                                )
                            )
                            val data: String =
                                cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.DATA))
                            val id = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media._ID))
                            val music = MusicData(id, -1, albumId, title, artist, "", data, duration, songNumber, dataPath)
                            songsList.add(music)
                            songNumber++
                        }
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace();
            } finally {
                cursor?.close()
            }
            return songsList
        }
    }
}

数据类MusicData

java 复制代码
import java.io.Serializable

data class MusicData(
    val id: Long,
    val artistId: Int,
    val albumId: Long,
    val title: String,
    val artist: String,
    val album: String,
    val data:String,
    val duration: Long,
    val songSize: Int,
    val path:String
) : Serializable
  1. 获取流派音乐数据
java 复制代码
   /**
         * 获取所有流派
         *
         * @param context
         * @return
         */
        @SuppressLint("Range")
        fun getGenres(context: Context): List<GenresData?> {
            val cursor = context.contentResolver.query(MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI, null, null, null, null)
            var genresList: MutableList<GenresData?> = ArrayList()
            if (cursor != null) {
                genresList = java.util.ArrayList(cursor.count)
                while (cursor.moveToNext()) {
                    val id = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Genres._ID))
                    val name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Genres.NAME))
                    genresList.add(GenresData(id, name))
                }
                cursor.close()
            }
            return genresList
        }

数据类

java 复制代码
data class GenresData(val id: Long, val name: String, val count: Int) {
}

获取艺术家

java 复制代码
  /**
     * 获取艺术家
     * @param context
     */
    fun getArtistsForCursor(context: Context): List<ArtistData> {
        val artistSortOrder = PreferencesUtility.getInstance(context).artistSortOrder
        val cursor: Cursor? = context.contentResolver.query(
            MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI,
            arrayOf(DATA, ARTIST, NUMBER_ALBUM, NUMBER_TRACK),
            null,
            null,
            artistSortOrder
        )

        val arrayList: MutableList<ArtistData> = ArrayList()
        if (cursor != null && cursor.moveToFirst()) do {
            val artist = ArtistData(
                cursor.getLong(0), cursor.getString(1), cursor.getInt(2), cursor.getInt(3)
            )
            arrayList.add(artist)
        } while (cursor.moveToNext())
        cursor?.close()
        return arrayList
    }

数据类

java 复制代码
data class ArtistData(val id: Long, val name: String, val count: Int, val num: Int) {
}

完整代码

java 复制代码
package com.zong.musiclib.helper

import android.annotation.SuppressLint
import android.content.ContentResolver
import android.content.Context
import android.database.Cursor
import android.provider.MediaStore
import com.zong.musiclib.utils.PreferencesUtility

object MusicHelper {

    private const val DATA = "_id"
    private const val ARTIST = "artist"
    private const val NUMBER_ALBUM = "number_of_albums"
    private const val NUMBER_TRACK = "number_of_tracks"

    @SuppressLint("Range")
    fun getMusic(context: Context): MutableList<MusicData> {
        var songNumber = 0
        val songsList: MutableList<MusicData> = ArrayList() //用于装歌曲数据

        val contentResolver: ContentResolver = context.contentResolver
        var cursor: Cursor? = null
        try {
            cursor = contentResolver.query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                null, null, null, null
            );
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    //是否是音频
                    val isMusic =
                        cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.IS_MUSIC))
                    //时长
                    val duration =
                        cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION))
                    //是音乐并且时长大于30秒
                    if (isMusic != 0 && duration >= 30 * 1000) {
                        //歌名
                        val title = cursor.getString(
                            cursor.getColumnIndexOrThrow(
                                MediaStore.Audio.Media.TITLE
                            )
                        )
                        //歌手
                        val artist = cursor.getString(
                            cursor.getColumnIndexOrThrow(
                                MediaStore.Audio.Media.ARTIST
                            )
                        );
                        //专辑id
                        val albumId =
                            cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID))
                        //文件路径
                        val dataPath = cursor.getString(
                            cursor.getColumnIndexOrThrow(
                                MediaStore.Audio.Media.DATA
                            )
                        )
                        val data: String =
                            cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.DATA))
                        val id = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media._ID))
                        val music = MusicData(id, -1, albumId, title, artist, "", data, duration, songNumber, dataPath)
                        songsList.add(music)
                        songNumber++
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace();
        } finally {
            cursor?.close()
        }
        return songsList
    }


    /**
     * 获取所有流派
     *
     * @param context
     * @return
     */
    @SuppressLint("Range")
    fun getGenres(context: Context): List<GenresData?> {
        val cursor = context.contentResolver.query(MediaStore.Audio.Genres.EXTERNAL_CONTENT_URI, null, null, null, null)
        var genresList: MutableList<GenresData?> = ArrayList()
        if (cursor != null) {
            genresList = java.util.ArrayList(cursor.count)
            while (cursor.moveToNext()) {
                val id = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Genres._ID))
                val name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Genres.NAME))
                genresList.add(GenresData(id, name))
            }
            cursor.close()
        }
        return genresList
    }


    /**
     * 获取艺术家
     * @param context
     */
    fun getArtistsForCursor(context: Context): List<ArtistData> {
        val artistSortOrder = PreferencesUtility.getInstance(context).artistSortOrder
        val cursor: Cursor? = context.contentResolver.query(
            MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI,
            arrayOf(DATA, ARTIST, NUMBER_ALBUM, NUMBER_TRACK),
            null,
            null,
            artistSortOrder
        )

        val arrayList: MutableList<ArtistData> = ArrayList()
        if (cursor != null && cursor.moveToFirst()) do {
            val artist = ArtistData(
                cursor.getLong(0), cursor.getString(1), cursor.getInt(2), cursor.getInt(3)
            )
            arrayList.add(artist)
        } while (cursor.moveToNext())
        cursor?.close()
        return arrayList
    }

}
相关推荐
阿巴斯甜20 小时前
Android 报错:Zip file '/Users/lyy/develop/repoAndroidLapp/l-app-android-ble/app/bu
android
Kapaseker21 小时前
实战 Compose 中的 IntrinsicSize
android·kotlin
xq95271 天前
Andorid Google 登录接入文档
android
黄林晴1 天前
告别 Modifier 地狱,Compose 样式系统要变天了
android·android jetpack
冬奇Lab1 天前
Android触摸事件分发、手势识别与输入优化实战
android·源码阅读
城东米粉儿2 天前
Android MediaPlayer 笔记
android
Jony_2 天前
Android 启动优化方案
android
阿巴斯甜2 天前
Android studio 报错:Cause: error=86, Bad CPU type in executable
android
张小潇2 天前
AOSP15 Input专题InputReader源码分析
android
_小马快跑_2 天前
Kotlin | 协程调度器选择:何时用CoroutineScope配置,何时用launch指定?
android