How to download and play remote media using MediaPlayer in UWP?

Harvinder Singh 1 Reputation point
2019-12-12T10:37:17.37+00:00

I am trying to play remote media using MediaPlayer and MediaSource created from CreateFromDownloadOperation, with the idea that media would start playing as soon as some meaningful data is downloaded through DownloadOperation. Also, I would be able to save it locally for the next time.

@jadailey
It was mentioned in the forum post sometime back here at https://social.msdn.microsoft.com/Forums/en-US/37b2650c-4d81-4448-91ea-c57be33d4c74/rs41803uwpc-media-player-mediasource-createfromdownloadoperation-deleted-download-files?forum=wpdevelop

Breeze asked me to take a look at this. Is there a particular reason that you are using the background download playback functionality in your app?

The intent of this functionality is to allow for immediate playback of an audio or video file while also caching the file locally for offline playback at a later date.

However, what I am finding is that the media does not start playing till the file is completely downloaded. I am on 1803, with Target set to 1903 and min target of 1803. Here is basics of my code

var destinationFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(  
    $"{filePathHash}", CreationCollisionOption.ReplaceExisting);  

var download = new BackgroundDownloader().CreateDownload(url, destinationFile);  
download.IsRandomAccessRequired = true;  

var task = Task.Run(async ()=> await download.StartAsync());  

mediaPlayer.Source = MediaSource.CreateFromDownloadOperation(download);   

However if I create mediaSource from MediaSource.CreateFromUri(), it starts playing almost immediately.

File used for testing https://www.thenakedscientists.com/sites/default/files/media/podcasts/episodes/Ask_19.12.06.mp3.

Universal Windows Platform (UWP)
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Nico Zhu (Shanghai Wicresoft Co,.Ltd.) 12,851 Reputation points
    2019-12-12T14:45:12.323+00:00

    How to download and play remote media using MediaPlayer in UWP?

    when you call CreateFromDownloadOperation method, it will start download automatically, you have no need call StartAsync. Please try following code.

    private async void MyMedia_Loaded(object sender, RoutedEventArgs e)  
    {  
        var destinationFile = await ApplicationData.Current.LocalFolder.CreateFileAsync($"file.mp3", CreationCollisionOption.ReplaceExisting);  
        var url = new Uri("https://www.thenakedscientists.com/sites/default/files/media/podcasts/episodes/Ask_19.12.06.mp3");  
        var download = new BackgroundDownloader().CreateDownload(url, destinationFile);  
        download.IsRandomAccessRequired = true;       
        MyMedia.Source = MediaSource.CreateFromDownloadOperation(download);        
        MyMedia.AutoPlay = true;  
    }