Home > OS >  My audio player on Android doesn't work - Xamarin
My audio player on Android doesn't work - Xamarin

Time:10-30

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?

CodePudding user response:

This seems to be a common exception with MediaPlayer.Prepare() on Android devices. A quick search turned up this:

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

Quote by Anonymous:

Hi, I wasted a lot of time, trying to find a solution to this issue on my side too. So I post here, just in case it is helping some people. My situation : I wanted to load an audio file from my assets (so not registered in my resources). I am using a similar code as Ike Nwaogu, except that I am using an AssetFileDescriptor to open my file (in my activity class code, so I have access to "Assets") :

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();
}

I was failing on the Prepare(). I tried to add the access to external storage permissions (but it did make sense since it was loaded from my assets directly, I tried just in case).

Just by chance, by seeing other people samples on the forums, I added the afd.StartOffset, afd.DeclaredLength to the parameters:

soundPlayer.SetDataSource(afd.FileDescriptor, afd.StartOffset, afd.DeclaredLength);

and it worked ... I don't know if it just luck and if is going to fail again later or if there is a bug in API ...

According to various sources, using getStartOffset and getLength when setting the DataSource should fix this:

player.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(), fileDescriptor.getLength());

Alternatively, here are a few more ideas: 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

  • Related