Search This Blog

Saturday 27 July 2019

Xamarin Android/iOS download and play video from URL


SaveAndPlayVideo.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="TestApp.SaveAndPlayVideo">
    <ContentPage.Content>
        <StackLayout  Margin="10,10,10,10">
            <Label Text="https://www.w3schools.com/html/mov_bbb.mp4" />
            <Button Text="Click Here to Play Video" x:Name="btnPlayVideo" Clicked="BtnPlayVideo_Clicked" />
            <WebView  x:Name="webView"  ></WebView>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

SaveAndPlayVideo.xaml.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using TestApp.Services;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace TestApp
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SaveAndPlayVideo  {
        public SaveAndPlayVideo()
{
InitializeComponent ();
        }


        private async void BtnPlayVideo_Clicked(object sender, EventArgs e)
        {
            string videoPath = "https://www.w3schools.com/html/mov_bbb.mp4";
            var client = new HttpClient();
            byte[] bytedata =null;
            var res = await client.GetAsync(videoPath);
       
                if(res.StatusCode == HttpStatusCode.OK)
                {
                      bytedata= await res.Content.ReadAsByteArrayAsync();
                }
            DependencyService.Get<IMediaService>().SaveAndPlayVideo(Path.GetFileName(videoPath), bytedata);
            }
        }
    }
 

Now create the IMediaService Interface and add the following Code.

IMediaService.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace TestApp.Services
{
   public interface IMediaService
    {
        void SaveAndPlayVideo(string fileName,byte[] imageByte);
    }
}    


Now Implement this interface in Platform-specific

TestApp.Android

Create the MediaService.cs Class that Implement IMediaService Interface.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Plugin.CurrentActivity;
using TestApp.Droid.Services;
using TestApp.Services;
using Xamarin.Forms;

[assembly: Xamarin.Forms.Dependency(typeof(MediaService))]
namespace TestApp.Droid.Services
{
    public class MediaService : IMediaService
    {
        Context CurrentContext => CrossCurrentActivity.Current.Activity;
        string rootPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyVideos);
        string folderName = "videoDir";
        public void SaveAndPlayVideo(string fileName, byte[] imageByte)
        {
            var directoryPath = Path.Combine(rootPath, folderName);
            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }
            var fullPath = Path.Combine(directoryPath, fileName);
            if (File.Exists(fullPath))
            {
                Intent intent = new Intent();
                intent.SetAction(Intent.ActionView);
                intent.SetDataAndType(Android.Net.Uri.Parse(fullPath), "video/*");
                ((Activity)CurrentContext).StartActivity(intent);
            }
            else
            {
                System.IO.File.WriteAllBytes(fullPath, imageByte);
                var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
                mediaScanIntent.SetData(Android.Net.Uri.FromFile(new Java.IO.File(fullPath)));
                CurrentContext.SendBroadcast(mediaScanIntent);

                Intent intent = new Intent();
                intent.SetAction(Intent.ActionView);
                intent.SetDataAndType(Android.Net.Uri.Parse(fullPath), "video/*");
                ((Activity)CurrentContext).StartActivity(intent);
            }
        }
    }
}

Note:   For accessing the CurrentContext  Install the NuGet Package (Plugin.CurrentActivity) from NuGet Package Manager  Also check for the external storage permission.


TestApp.iOS

Create the MediaService.cs Class that Implement IMediaService Interface.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using AVFoundation;
using AVKit;
using Foundation;
using TestApp.iOS.Services;
using TestApp.Services;
using UIKit;

[assembly:Xamarin.Forms.Dependency(typeof(MediaServicecs)) ]
namespace TestApp.iOS.Services
{
    public class MediaServicecs : IMediaService
    {
        string rootPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
        string folderName = "videoDir";
        public void SaveAndPlayVideo(string fileName,byte[] imageByte )
        {
            var directoryPath = Path.Combine(rootPath, folderName);
            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }
            var viewController = UIApplication.SharedApplication.KeyWindow.RootViewController;

            while (viewController.PresentedViewController != null)
            {
                viewController = viewController.PresentedViewController;
            }
            var fullPath = Path.Combine(directoryPath, fileName);

            if (File.Exists(fullPath))
            {
                var url = new NSUrl(fullPath, false);
                var avp = new AVPlayer(url);
                var avpvc = new AVPlayerViewController();
                avpvc.Player = avp;
                avp.Play();
                viewController.PresentViewController(avpvc, animated: true, completionHandler: null);
            }
            else
            {
                File.WriteAllBytes(fullPath, imageByte);
                var url = new NSUrl(fullPath, false);
                var avp = new AVPlayer(url);
                var avpvc = new AVPlayerViewController();
                avpvc.Player = avp;
                avp.Play();
                viewController.PresentViewController(avpvc, animated: true, completionHandler: null);
            }
         

        }
    }
}

No comments:

Post a Comment

Popular Posts