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
    }

}
相关推荐
Хайде3 分钟前
C++复习
开发语言·c++
weixin_455446173 分钟前
js中的=、==与===的区别
开发语言·javascript·ecmascript
zls3653654 分钟前
C#开发最快的浏览器,打造极速浏览体验
开发语言·c#
晚渔声6 分钟前
【网络】网络抓包与协议分析
开发语言·网络·wireshark
麻花疼不疼8 分钟前
php 使用mqtt
android·开发语言·php
安girl9 分钟前
springMVC重点知识
java·开发语言
零希10 分钟前
html数据类型
开发语言·前端·javascript
Ysjt | 深14 分钟前
深入理解 C++ 二叉树
开发语言·数据结构·c++
五羟基己醛36 分钟前
【C++入门(一)】半小时入门C++开发(深入理解new+List+范围for+可变参数)
开发语言·c++
码路刺客36 分钟前
一学就废|Python基础碎片,列表(List)
开发语言·python