Android MediaPlayer stutters (complete short example included)

ispiroispiro USMember ✭✭
edited February 2017 in Xamarin.Android

The following Xamarin.Forms app plays an mp3 file while showing the user a Slider for seeking in the music. The Slider does not update according to the position in the music. It's only for seeking.

The problem is that when seeking a couple of times, it starts stuttering - jumping forward and backwards on its own for several seconds. Especially when seeking back and forth close by, like from second-10 to second-12 and back several times. (On a more complex app it was shown that MediaPlayer returns the correct CurrentPosition.) I assume this has to do with some internal cache for decoded sound (from mp3 to wav) but I don't know how to check that. I tried this with several mp3 files.

How can this be prevented?

The App:

public class App : Application
{
    public Slider slider = new Slider();
    public static App ThisApp;
    IMedia imedia = DependencyService.Get<IMedia>();

    public App()
    {
        ThisApp = this;
        var content = new ContentPage
        {
            Title = "Test",
            Content = new StackLayout
            {
                VerticalOptions = LayoutOptions.Center,
                Children =
                {
                    slider
                }
            }                
        };
        MainPage = new NavigationPage(content);
        slider.ValueChanged += Slider_ValueChanged;
        imedia.Start();
    }

    void Slider_ValueChanged(object sender, ValueChangedEventArgs e)
    {
        imedia.Seek((int)e.NewValue);
    }

    protected override void OnStart()
    ...
}

The interface:

public interface IMedia
{
    void Start();
    void Seek(int i);
}

The Droid part:

public class Media1 : IMedia
{
    MediaPlayer player;

    public void Start()
    {
        player = MediaPlayer.Create(Xamarin.Forms.Forms.Context,
            Android.Net.Uri.Parse(
                Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryMusic) 
                + "/example.mp3"));
        player.Prepared += Player_Prepared;
    }

    void Player_Prepared(object sender, EventArgs e)
    {
        App.ThisApp.slider.Maximum = player.Duration;
        player.Start();
    }

    public void Seek(int i)
    {
        player.SeekTo(i);
    }
}

Thing I tried:

  • The files - they don't stutter on the Google Play app
  • The sdk etc. - I set all 3 settings to Android M (6) since that's what I have on my phone (Samsung J5)
  • I tried pausing before seeking and only playing again on the SeekComplete.
  • I avoided seeking while seeking by using a flag and only resetting it on SeekComplete.

Nothing helped.

I'm using Visual Studio 2015.

Sign In or Register to comment.