Xamarin for android:无法从外部文件夹播放 mp3
Posted
技术标签:
【中文标题】Xamarin for android:无法从外部文件夹播放 mp3【英文标题】:Xamarin for android: unable to play mp3 from external folder 【发布时间】:2020-09-28 17:08:55 【问题描述】:我无法播放放在应用程序外部存储文件夹中的 mp3 文件。
我在 OnCreate() 中请求了权限
private const int EXTERNAL_READ_WRITE_REQUEST = 1337;
protected override async void OnCreate(Bundle savedInstanceState)
ActivityCompat.RequestPermissions(this, new string[]
Manifest.Permission.ReadExternalStorage,
Manifest.Permission.WriteExternalStorage
,
EXTERNAL_READ_WRITE_REQUEST);
然后我验证了权限已被授予:
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] android.Content.PM.Permission[] grantResults)
if (requestCode == EXTERNAL_READ_WRITE_REQUEST)
if (grantResults.ToArray().ToList().IndexOf(Permission.Denied) == -1)
ShowMessage("Permissions granted");
else
ShowMessage("Permission request denied, unable to continue.");
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
然后在服务(不是活动)中检查权限,获取文件夹,获取文件,并尝试使用 MediaPlayer 类播放 mp3:
MediaPlayer player;
public string GetSongDirectory()
string result = "";
List<Java.IO.File> files = GetExternalFilesDirs(null).ToList();
files = files.OrderBy(x => x.AbsolutePath.IndexOf("emulated")).ToList();
var f = files.DefaultIfEmpty(null).FirstOrDefault();
if (f != null)
result = f.AbsolutePath + "/songs";
if (Directory.Exists(result) == false)
Directory.CreateDirectory(result);
return result;
[return: GeneratedEnum]
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
string songFolder = GetSongDirectory();
var p = ContextCompat.CheckSelfPermission(this.ApplicationContext, Manifest.Permission.ReadExternalStorage);
if (p == Android.Content.PM.Permission.Granted)
try
foreach (string fileName in System.IO.Directory.GetFiles(songFolder, "*.*", SearchOption.AllDirectories))
player = new MediaPlayer();
JFile f = new JFile(fileName);
Java.IO.FileInputStream fs = new FileInputStream(f);
player.Reset();
//player.SetDataSource(fileName); this didn't work either
player.SetDataSource(fs.FD, 0L, f.Length());
player.Prepare();
player.Start();
break;
catch (Exception x)
x.ToString();
Toast.MakeText(this, "Greetings from serivce", ToastLength.Long).Show();
return StartCommandResult.Sticky;
但是,在调用 Prepare 时,它会引发异常:
Java.IO.IOException: Prepare failed.: status=0x1
at Java.Interop.JniEnvironment+InstanceMethods.CallVoidMethod
文件名包含“/storage/1606-3C08/Android/data/com.companyname.mypod/files/songs/IshDARR - Alpha.mp3”
当它属于外部 SD 卡时,如何从我的 xamarin 服务中播放此 mp3 文件?
编辑:我可以使用 BinaryReader 读取文件的内容,因此它不是文件访问权限问题。
【问题讨论】:
@WendyZang-MSFT 我需要播放用户的音乐,而不是我自己的声音文件 【参考方案1】:我在网上找到了答案,但是失去了原作者所以是如何在xamarain上从外部sd卡播放mp3:
public class StreamMediaDataSource : MediaDataSource
System.IO.Stream data;
public StreamMediaDataSource(System.IO.Stream Data)
data = Data;
public override long Size
get
return data.Length;
public override int ReadAt(long position, byte[] buffer, int offset, int size)
data.Seek(position, System.IO.SeekOrigin.Begin);
return data.Read(buffer, offset, size);
public override void Close()
if (data != null)
data.Dispose();
data = null;
protected override void Dispose(bool disposing)
base.Dispose(disposing);
if (data != null)
data.Dispose();
data = null;
这是一个sn-p:
StreamReader sr = new StreamReader(fileName);
player.SetDataSource(new StreamMediaDataSource(sr.BaseStream));
player.Prepare();
player.Start();
我认为它失败的原因是它用于读取文件的方法。
如果我尝试使用 FileStream 读取文件。即使它已通过用户提示通过它授予访问权限,它也会引发访问被拒绝异常。
这是 java 日志,以防万一有人需要通过 google 搜索它:
06-10 11:37:26.048 E/MediaPlayerNative(31944): error (1, -2147483648)
06-10 11:37:26.175 D/Mono (31944): DllImport searching in: '__Internal' ('(null)').
06-10 11:37:26.175 D/Mono (31944): Searching for 'java_interop_jnienv_call_object_method'.
06-10 11:37:26.175 D/Mono (31944): Probing 'java_interop_jnienv_call_object_method'.
06-10 11:37:26.176 D/Mono (31944): Found as 'java_interop_jnienv_call_object_method'.
【讨论】:
以上是关于Xamarin for android:无法从外部文件夹播放 mp3的主要内容,如果未能解决你的问题,请参考以下文章
在xamarin android中无法从FirebaseAuth获取刷新令牌。
无法在 Xamarin Android 中将图像从资源设置为自定义 ImageView?