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

Ashwini 26 Reputation points
2021-06-25T07:04:55.15+00:00

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

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,291 questions
0 comments No comments
{count} vote

Accepted answer
  1. Kyle Wang 5,531 Reputation points
    2021-06-28T07:51:26.45+00:00

    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 person found this answer helpful.

0 additional answers

Sort by: Most helpful