当前位置: 首页 > article >正文

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

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

1. 获取全部音乐数据

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

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

2. 获取流派音乐数据

   /**
         * 获取所有流派
         *
         * @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
        }

数据类

data class GenresData(val id: Long, val name: String, val count: Int) {
}

获取艺术家

  /**
     * 获取艺术家
     * @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
    }

数据类

data class ArtistData(val id: Long, val name: String, val count: Int, val num: Int) {
}

完整代码

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
    }

}


http://www.kler.cn/a/406561.html

相关文章:

  • 调大Vscode资源管理器字体
  • Kafka 数据倾斜:原因、影响与解决方案
  • 小鹏汽车智慧材料数据库系统项目总成数据同步
  • 跟李笑来学美式俚语(Most Common American Idioms): Part 29
  • 空间数据存储格式GeoJSON
  • BugJson因为json格式问题OOM怎么办
  • Spring Boot 3.0废弃了JavaEE,改用了Jakarta EE
  • Linux云平台Oracle 12c安装与数据迁移
  • 大数据-231 离线数仓 - DWS 层、ADS 层的创建 Hive 执行脚本
  • el-tree扩展vue-easy-tree虚拟树的使用(解决页面卡顿)
  • 力扣 LeetCode 701. 二叉搜索树中的插入操作(Day10:二叉树)
  • wpf 事件转命令的方式
  • 【微服务】Spring AI 使用详解
  • [模版总结] - 树的基本算法4 -最近公共祖先 LCA
  • python语言基础
  • C/C++基础知识复习(26)
  • 【遵守孤儿规则的External trait pattern】
  • Python 爬虫 (1)基础 | 基础操作
  • python语言基础-5 进阶语法-5.5 上下文管理协议(with语句)
  • 第31次CCF计算机软件能力认证
  • 相机触发模式
  • Appium常用的使用方法(一)
  • 上生产时连接mysql数据库总是被拒绝
  • HarmonyOs鸿蒙开发实战(20)=>一文学会基础使用组件导航Navigation
  • 网络安全-web架构-nginx配置
  • node.js fluent-ffmpeg 桌面推流