question

Ashwini-0407 avatar image
0 Votes"
Ashwini-0407 asked KyleWang-MSFT edited

How to Download video to local stoarge and How to play downloaded video offline

Hi ,

I am working on playing video in Xamarin forms application.
I have used Xamarin.CommunityToolkit package to play video.

Could anyone tell me how to download video from url to local storage and the play same video offline inside the application...

Thanks in Advance


dotnet-xamarin
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

KyleWang-MSFT avatar image
0 Votes"
KyleWang-MSFT answered KyleWang-MSFT edited

Hi Ashwini-0407,

Welcome to our Microsoft Q&A platform!

If you are using MediaElement to play the video. You don't need to download it. You can set the Source property to the URI of the media file directlly.

To download the video, you can use class "HttpClient".

 List<string> urls = new List<string>() { "https://test.mp4" };
 // define the HttpClient
 var handler = new HttpClientHandler { AllowAutoRedirect = false };
 var client = new HttpClient(handler);
    
 System.Threading.Tasks.Parallel.ForEach(urls, async (url) =>
 {
     var uri = new Uri(url);
     var fileName = System.IO.Path.GetFileName(uri.LocalPath);
     //var path = Path.Combine(Xamarin.Essentials.FileSystem.AppDataDirectory, "test.mp4");
    
     // download the file
     var data = await client.GetByteArrayAsync(uri);
     var path = System.IO.Path.Combine(Xamarin.Essentials.FileSystem.AppDataDirectory, fileName);
     // save file on disk
     System.IO.File.WriteAllBytes(path, data);
 });

Update
According to the document, you can download and save the stream to "local" or "temp" folder.

 public async Task CopyVideoIfNotExists()
 {
     string url = @"https://sec.ch9.ms/ch9/5d93/a1eab4bf-3288-4faf-81c4-294402a85d93/XamarinShow_mid.mp4";
     using (var client = new WebClient())
     {
         var content = client.DownloadData(url);
         var stream = new MemoryStream(content);
    
         string folder = FileSystem.AppDataDirectory;
         //string folder = Path.GetTempPath();
         string videoFile = Path.Combine(folder, "XamarinShow.mp4");
    
         if (!File.Exists(videoFile))
         {
             using (FileStream outputStream = File.Create(videoFile))
             {
                 await stream.CopyToAsync(outputStream);
             }
         }
     }
    
     MediaSource = "local/XamarinShow.mp4";
 }

Also, don't fogget to implement interface "INotifyPropertyChanged" for property "MediaSource".

 string mediaSource;
    
 public string MediaSource
 {
     get => mediaSource;
     set
     {
         mediaSource = value;
         OnPropertyChanged("MediaSource");
     }
 }
    
 public event PropertyChangedEventHandler PropertyChanged;
    
 protected void OnPropertyChanged(string propertyName)
 {
     var handler = PropertyChanged;
     if (handler != null)
         handler(this, new PropertyChangedEventArgs(propertyName));
 }

As mentioned in the document, you need to create VideoSourceConverter for "MediaSource".

 public class VideoSourceConverter : IValueConverter
 {
     public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
     {
         if (value == null)
             return null;
    
         if (string.IsNullOrWhiteSpace(value.ToString()))
             return null;
    
         string url = $"ms-appdata:///{value}";
    
         return new Uri(url);
     }
    
     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
     {
         throw new NotImplementedException();
     }
 }

And here is the xaml.

 <xct:MediaElement Source="{Binding MediaSource, Converter={StaticResource VideoSourceConverter}}"
         ShowsPlaybackControls="True" VerticalOptions="FillAndExpand"/>

Regards,
Kyle


If the response is helpful, please click "Accept Answer" and upvote it.

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi anonymous userWang-MSFT ,

Thanks for your Answer. Yes I am using Media element to stream video when user is online.
I wanted to download video and display when user is offline.
How to display downloaded video? could you please answer

0 Votes 0 ·