c# - My audio player on Android doesn't work - Xamarin
问题描述
I program C# Android app using Xamarin. I wrote this code:
protected MediaPlayer player;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.layout1);
this.Window.AddFlags(WindowManagerFlags.Fullscreen);
player = new MediaPlayer();
player.Reset();
var fileDescriptor = Assets.OpenFd("MySound.mp3");
player.SetDataSource(fileDescriptor.FileDescriptor);
player.Prepare();
player.Start();
}
MySound.mp3 file is direct in the Assets folder. When I run app there is an error:
Java.IO.IOException Message=Prepare failed.: status=0x1
in the line with player.Prepare();
What is wrong? Why it's no working?
解决方案
这似乎是 Android 设备上 MediaPlayer.Prepare() 的常见例外。快速搜索出现了这个:
匿名引用:
嗨,我浪费了很多时间,也试图找到解决这个问题的方法。所以我在这里发帖,以防万一它对某些人有所帮助。我的情况:我想从我的资产中加载一个音频文件(所以没有在我的资源中注册)。我正在使用与 Ike Nwaogu 类似的代码,除了我使用 AssetFileDescriptor 打开我的文件(在我的活动类代码中,因此我可以访问“资产”):
string path = "Audio/myfile.ogg"; Android.Content.Res.AssetFileDescriptor afd = Assets.OpenFd(path); MediaPlayer soundPlayer = new MediaPlayer(); if (afd != null) { soundPlayer.Reset(); soundPlayer.SetDataSource(afd.FileDescriptor); soundPlayer.Prepare(); soundPlayer.Enabled = true; afd.Close(); }
我在 Prepare() 上失败了。我尝试添加对外部存储权限的访问(但这确实有意义,因为它是直接从我的资产中加载的,我尝试以防万一)。
偶然地,通过在论坛上看到其他人的示例,我将 afd.StartOffset、afd.DeclaredLength 添加到参数中:
soundPlayer.SetDataSource(afd.FileDescriptor, afd.StartOffset, afd.DeclaredLength);
它奏效了......我不知道它是否只是运气,以后是否会再次失败,或者API中是否存在错误......
根据各种来源,在设置 DataSource 时使用 getStartOffset 和 getLength 应该可以解决这个问题:
player.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(), fileDescriptor.getLength());
或者,这里还有一些想法: Android MediaPlayer throwing "Prepare failed.: status=0x1" on 2.1, works on 2.2
https://forum.processing.org/two/discussion/6722/andriod-mediaplayer-prepare-failed-status-0x1
推荐阅读
- java - 使用多模块 Maven 项目时 Eclipse 的类路径问题
- java - 将 JTable 中的数据导出为 PDF 格式
- google-apps-script - 我需要一个优雅的解决方案来格式化比赛时间
- c# - 如果与 Task.WhenAll() 一起使用,键入的 http 客户端会引发套接字异常
- batch-file - 从文本文件中提取部分句子
- ansible - 我可以在 ansible 中设置一个任务以仅在文件夹存在的情况下运行吗?
- cygwin - 关于 Cygwin Windows 编译问题的 Wine
- python - PyNGL/PyNio 的资源文件问题
- c++ - 密码生成器:如何让每个密码换行?
- c - 如何阅读最后一个字符为“n”的句子