MediaPlayer Async

ispirLee25ispirLee25 Member ✭✭
edited June 2018 in Xamarin.Android

Hi Guys!

            var mediaUri = Android.Net.Uri.Parse(mediaUrl);
            mp = MediaPlayer.Create(this, mediaUri);

This code block is slow running.I want to this block convert to async method? How can i it?

Answers

  • robbitrobbit CNMember Xamurai

    Hi @ispirLee25 ,

    Form official document, the create method:

    Convenience method to create a MediaPlayer for a given Uri. On success, prepare() will already have been called and must not be called again.

    The prepare() method will called automatically, so you can't call prepareAsync.

    So, you can read this, use MediaPlayer mediaPlayer = new MediaPlayer(); and SetDataSource, and then you can use prepareAsync. If you use prepareAsync you need use setOnPreparedListener method to listener to the onPrepared event.

    Please refer to this case.

  • JGoldbergerJGoldberger USMember, Forum Administrator, Xamarin Team, University Xamurai
    edited July 2018

    @ispirLee25 said:
    Hi Guys!

                var mediaUri = Android.Net.Uri.Parse(mediaUrl);
                mp = MediaPlayer.Create(this, mediaUri);
    

    This code block is slow running.I want to this block convert to async method? How can i it?

    Another option in addition to the one supplied by robbit is to create your own async method

    public async Task<MediaPlayer> PrepareMedia(Android.Net.Uri mediaUri)
        {
            MediaPlayer mediaPlayer = null;
            await Task.Run(() =>
            {
                mediaPlayer = MediaPlayer.Create(this, mediaUri);
            });
            return mediaPlayer;
        }
    

    then call it:

    var mediaUri = Android.Net.Uri.Parse(mediaUrl);
    mp = await PrepareMedia(mediaUri);
    

    you will have to add the async keyword to the method that the above two lines of code are in so you can use await.

Sign In or Register to comment.