Android,Xamarin:从SD卡上的特定位置获取mp3,然后转换为URI进行播放

时间:2018-10-04 07:27:12

标签: android xamarin media

我目前正在开发一个小应用,可以播放音乐。要测试我的应用,我想播放存储在我的SD卡中的mp3:

SD-Card/Music/MYFILE.mp3

这需要适合这里:

private void InitPlayer() {
    mediaPlayer = MediaPlayer.Create(this, "URI TO MY FILE");
}

因此,我基本上需要获取指向我文件的uri链接。我还没有找到解决方法。有人可以帮我吗?

谢谢:)

1 个答案:

答案 0 :(得分:1)

我在Xamarin论坛上发现了包含以下方法的帖子。

https://forums.xamarin.com/discussion/103478/how-to-get-path-to-external-sd-card

public static string GetBaseFolderPath( bool getSDPath = false )
{
   string baseFolderPath = "";

   try
   {
      Context context = Application.Context;
      Java.IO.File[] dirs = context.GetExternalFilesDirs( null );

      foreach ( Java.IO.File folder in dirs )
      {
        bool IsRemovable = Android.OS.Environment.InvokeIsExternalStorageRemovable( folder );
        bool IsEmulated = Android.OS.Environment.InvokeIsExternalStorageEmulated( folder );

        if ( getSDPath ? IsRemovable && !IsEmulated : !IsRemovable && IsEmulated )
            baseFolderPath = folder.Path;
      }
   }
   catch ( Exception ex )
   {
      Console.WriteLine( "GetBaseFolderPath caused the follwing exception: {0}", ex );
   }

   return baseFolderPath;
}

获得basefolderPath后,可以通过将其添加到地址(basefolderPath字符串)来访问音乐文件夹和文件。

例如

baseFolderPath += "/YOUR_MUSIC_FOLDER/YOUR_MUSIC_FILE"

添加到第二个问题

要单独进入存储文件夹,请使用以下方法:

Android.OS.Environment.getExternalStorageDirectory()

在使用此方法之前,您可能需要在清单中添加以下权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />