从Android

时间:2018-03-24 21:00:51

标签: android audio xamarin.android metadata

我想检索设备上歌曲的元数据(艺术家,专辑,路径,名称,长度)。这是我正在使用的代码。

 String selection = MediaStore.Audio.Media.InterfaceConsts.IsMusic + " != 0";

        String[] projection = {
                MediaStore.Audio.Media.InterfaceConsts.Artist,                  //artist
                MediaStore.Audio.Media.InterfaceConsts.Album,                   //album
                MediaStore.Audio.Media.InterfaceConsts.Data,                    //path
                MediaStore.Audio.Media.InterfaceConsts.DisplayName,             //title
                MediaStore.Audio.Media.InterfaceConsts.Duration
                };

        var cursor = myContentResolver.Query(
                MediaStore.Audio.Media.ExternalContentUri,
                projection,
                selection,
                null,
                null);


        while (cursor.MoveToNext())
        {
            string path = cursor.GetString(2); string name = cursor.GetString(3); string artist =  cursor.GetString(0); string album cursor.GetString(1); string duration = cursor.GetString(4);

        }

此代码的问题是歌曲的长度不正确。对于某些歌曲,它返回的时间比应该的短。所以我只使用一段代码来获取歌曲的长度。这是代码:

        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        mmr.SetDataSource(path);  //path is the path of the song file
        lenth = mmr.ExtractMetadata(MetadataKey.Duration);

但此代码还有另一个问题。对于某些歌曲,我在第2行得到例外:

Java.Lang.RuntimeException: setDataSource failed: status = 0x80000000

我还想说我正在使用权限:

Manifest.Permission.ReadExternalStorage,
 Manifest.Permission.Internet

我正在为我的项目使用Xamarin.Android。

1 个答案:

答案 0 :(得分:0)

此代码有效

公共列表getAllAudioFromDevice(最终上下文上下文){

    final List<MusicFilesModal> tempAudioList = new ArrayList<>();

    Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    String[] projection = {MediaStore.Audio.AudioColumns.DATA, MediaStore.Audio.AudioColumns.ALBUM,
            MediaStore.Audio.ArtistColumns.ARTIST,
            MediaStore.Audio.Media.DURATION};


    Cursor c = context.getContentResolver().query(uri, projection, null, null, null);

    if (c != null) {
        while (c.moveToNext()) {

            String path = c.getString(0);
            String album = c.getString(1);
            String artist = c.getString(2);
            String duration = c.getString(3);

            String title = path.substring(path.lastIndexOf("/") + 1);

            MusicFilesModal audioModel = new MusicFilesModal(path, title, artist, album, duration);

            //Log.e("Name :" + title, " Album :" + album);
            //Log.e("Path :" + path, " Artist :" + artist);

            Log.d("artistName_", artist);
            Log.d("albumName_", album);

            tempAudioList.add(audioModel);
        }
        c.close();
    }
    Log.d("tempAudioListSize_", tempAudioList.size() + "_");

    return tempAudioList;
}