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);
            }
         

        }
    }
}

Tuesday 23 July 2019

How to search data from Group Listview

listviewObject.ItemsSource =
                ListItemData.Where(f => f.Any(z => z.Title.ToLower().Contains(searchText.ToLower())));

Saturday 13 July 2019

Xamarin Form Play Video In WebView









Xamarin Form Code
Create Xaml Page and add the following Code

PlayVideoWithWebView.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.PlayVideoWithWebView">
    <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 In Default Player" x:Name="btnPlayVideo" Clicked="BtnPlayVideo_Clicked" />
            <WebView  x:Name="webView"  ></WebView>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>



PlayVideoWithWebView.xaml.cs


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
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 PlayVideoWithWebView : INotifyPropertyChanged
    {
        public event EventHandler<PageOrientationEventArgs> OnOrientationChanged = (e, a) => { };
        private double _width = 0;
        private double _height = 0;
        public PlayVideoWithWebView ()
{
InitializeComponent ();
            OnOrientationChanged += DeviceRotated;
        }

      
        protected override void OnSizeAllocated(double width, double height)
        {
            base.OnSizeAllocated(width, height);

            var oldWidth = _width;
            const double sizenotallocated = -1;

            base.OnSizeAllocated(width, height);
            if (Equals(_width, width) && Equals(_height, height)) return;

            _width = width;
            _height = height;

            // ignore if the previous height was size unallocated
            if (Equals(oldWidth, sizenotallocated)) return;

            // Has the device been rotated ?
            if (!Equals(width, oldWidth))
                OnOrientationChanged.Invoke(this, new PageOrientationEventArgs((width < height) ? PageOrientation.Vertical : PageOrientation.Horizontal));

        }

// called when the device orientation changed
        private void DeviceRotated(object sender, PageOrientationEventArgs e)
        {
            switch (e.Orientation)
            {
                case PageOrientation.Horizontal:
                    webView.HeightRequest = this._height;
                    webView.WidthRequest = this._width;
                    break;
                case PageOrientation.Vertical:
                    webView.HeightRequest = this._height / 2.5;
                    webView.WidthRequest = this._width;
                    break;
                default:
                    break;

            }
        }
        private void BtnPlayVideo_Clicked(object sender, EventArgs e)
        {
            webView.HeightRequest = this._height / 2.5;
            webView.WidthRequest = this._width;
            webView.Source = "https://www.w3schools.com/html/mov_bbb.mp4";
        }
    }

}


Create the PageOrientationEventArgs class for Handling Device Orientation.

PageOrientationEventArgs

using System;
using System.Collections.Generic;
using System.Text;
namespace TestApp.Services
{
    public class PageOrientationEventArgs : EventArgs
    {
        public PageOrientationEventArgs(PageOrientation orientation)
        {
            Orientation = orientation;
        }

        public PageOrientation Orientation { get; }
    }

    public enum PageOrientation
    {
        Horizontal = 0,
        Vertical = 1,
    }
}


Xamarin Android Play Video From URL In Default Media Player





Xamarin Form Code
Create Xaml Page and add following Code

MainPage.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"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="TestApp.MainPage">

    <StackLayout Margin="10,10,10,10">
        <Label Text="https://www.w3schools.com/html/mov_bbb.mp4" />
        <Button Text="Click Here to Play Video In Default Player" x:Name="btnPlayVideo" Clicked="BtnPlayVideo_Clicked" />
    </StackLayout>
</ContentPage>


MainPage.xaml.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TestApp.Services;
using Xamarin.Forms;

namespace TestApp
{
    // Learn more about making custom code visible in the Xamarin.Forms previewer
    // by visiting https://aka.ms/xamarinforms-previewer
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void BtnPlayVideo_Clicked(object sender, EventArgs e)
        {
            DependencyService.Get<IMediaService>().PlayVideo("https://www.w3schools.com/html/mov_bbb.mp4");
        }
    }
}

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 PlayVideo(string uri);
    }
}

Now Implement this interface in Platform specific

TestApp.Android

Create the MediaService.cs Class that Implement IMediaService Interface.

MediaService.cs

using System;
using System.Collections.Generic;
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;

[assembly: Xamarin.Forms.Dependency(typeof(MediaService))]
namespace TestApp.Droid.Services
{
    public class MediaService : IMediaService
    {
        Context CurrentContext => CrossCurrentActivity.Current.Activity;
        public void PlayVideo(string uri)
        {
            Intent intent = new Intent();
            intent.SetAction(Intent.ActionView);
            intent.SetDataAndType(Android.Net.Uri.Parse(uri), "video/*");
            ((Activity)CurrentContext).StartActivity(intent);
        }
    }
}

Note:   For accessing the CurrentContext  Install the NuGet Package (Plugin.CurrentActivity) from NuGet Package Manager 

Popular Posts