首页 > 解决方案 > 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?

标签: c#androidxamarinaudio

解决方案


这似乎是 Android 设备上 MediaPlayer.Prepare() 的常见例外。快速搜索出现了这个:

https://social.msdn.microsoft.com/Forums/en-US/15f9c371-1b8d-4927-9555-f40e2829c377/mediaplayer-prepare-failed-stauts0x1?forum=xamarinandroid

匿名引用:

嗨,我浪费了很多时间,也试图找到解决这个问题的方法。所以我在这里发帖,以防万一它对某些人有所帮助。我的情况:我想从我的资产中加载一个音频文件(所以没有在我的资源中注册)。我正在使用与 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


推荐阅读