Search code examples
c#androidxamarin.androidandroid-mediaplayer

Android Media Player randomly raises error and doesn't play


I am making an instrument playing app ("Walkband" style) on Xamarin.Android for VS2017. I have an array of MediaPlayers called players.

This is the Play function, where resid is equivalent to Resource.Raw.filename:

public void Play(int resid)
    {
        for (int i = 0; i < players.Length; i++)
        {
            if (!players[i].IsPlaying)
            {
                players[i].Reset();
                players[i] = MediaPlayer.Create(this, resid);
                players[i].Start();
                break;
            }
        }
    }

Most of the time it plays great, but occasionally (specifically after playing many resources in quick succession), it fails to play.

The log looks like this when it succeeds:

06-04 14:52:26.112 I/MediaPlayer(17611): message received msg=2, ext1=0, ext2=0
06-04 14:52:26.112 I/MediaPlayer(17611): playback complete

And like this when it fails:

06-04 14:52:25.933 I/MediaPlayer(17611): message received msg=100, ext1=1, ext2=-19
06-04 14:52:25.933 E/MediaPlayer(17611): error (1, -19)
06-04 14:52:25.933 E/MediaPlayer(17611): Error (1,-19)

The resource itself isn't the issue, as all the resources mostly work, and all occasionally fail


Solution

  • I have an array of MediaPlayers called players.

    You need to use soundpool, and please refer to this.