Search This Blog

Sunday, August 25, 2019

Flutter - Playing local, network and youtube videos with video player plugin.

If you're creating an application that supports videos feature then you have to use a video player. The Flutter team have created a Video Player widget to display a video in Flutter application.

flutter video player example
The Video Player widget can play multiple types of videos that may be stored in the mobile, as an asset, and from the internet. This plugin allows flutter to interface with the platform's native video players. In iOS, the video player widget uses AVPlayer to handle playback and it does not work on iOS simulators. So, you have to test videos on real iOS devices. In Android, the video player widget uses ExoPlayer to play a video. 

In this post, we going to explain a very basic use of video player that'll play video from application asset, from network and youtube url video.

flutter video player example from internet url

Creating a new Project
1. Create a new project from File ⇒ New Flutter Project with your development IDE.
2. Now,  add the video player plugin video_player as a dependency in the pubspec.yaml file. Once you do that, you need to run flutter packages get.


Android:- Add internet permission in the Android Manifest.xml(android/app/src/main/AndroidManifest.xml) file that we use for play online video.

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application ...>
    </application>
    <uses-permission android:name="android.permission.INTERNET"/>
</manifest>

iOS:- Add following key and value in the Info.plist (ios/Runner/Info.plist) file.

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSAllowsArbitraryLoads</key>
  <true/>
</dict>


3. After that open main.dart file and edit it. As we have set our theme and change debug banner property of Application. To control a video with video player, we have to create an instance of the VideoPlayerController. The VideoPlayerController provides different constructors to play videos from assets, files, and the internet. Before playing a video, we have to initialize the controller. It'll establish a connection with video and prepares the controller for playback.
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
void main() {
  runApp(VideoPlayer());
}
class VideoPlayer extends StatefulWidget {
  VideoPlayer({Key key}) : super(key: key);
  @override
  _VideoPlayerState createState() => _VideoPlayerState();
}
class _VideoPlayerState extends State<VideoPlayer> {
  VideoPlayerController _controller;
  Future<void> _initializeVideoPlayerFuture;

  @override
  void initState() {
    _controller = VideoPlayerController.asset(
      'local path',
    );
    _initializeVideoPlayerFuture = _controller.initialize();
    super.initState();
  }
  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Webview Widget',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primaryColor: const Color(0xFF02BB9F),
        primaryColorDark: const Color(0xFF167F67),
        accentColor: const Color(0xFF02BB9F),
      ),
      home: SizedBox(),
    );
  }
}

after the use of VideoPlayerController instance, we have to dispose instance of  VideoPlayerController. As we have implemented in dispose() method.



4
. It's time to add a video player widget in the hierarchy of screen. The video player plugin provides the VideoPlayer widget to display the video. The VideoPlayer widget takes up as much space as possible. This often isn’t ideal for videos because they are meant to be displayed in a specific aspect ratio, such as 16x9 and 4x3. Therefore, wrap the video player widget in an AspectRatio widget to ensure that the video has the correct proportions.


@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Video Example'),
      ),
      body: Center(
          child: AspectRatio(
              aspectRatio: 16 / 9,
              child: Container(
                child: (playerController != null
                    ? VideoPlayer(
                  playerController,
                )
                    : Container()),
              ))),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          createVideo();
          playerController.play();
        },
        child: Icon(Icons.play_arrow),
      ),
    );
  }

we using FloatingActionButton widget to create an instance of VideoPlayerController and play it.

void createVideo() {
    if (playerController == null) {
      playerController = VideoPlayerController.network(
          "https://r1---sn-aigl6nek.googlevideo.com/videoplayback?expire=1566678355&ei=80hhXeK-EJWvhAeftqiwBA&ip=185.27.134.50&id=o-ACa4cikYptSHAdpKCzCJjFMq2Gnt86FkIFLBC3wJevT2&itag=22&source=youtube&requiressl=yes&mm=31%2C29&mn=sn-aigl6nek%2Csn-aigzrn76&ms=au%2Crdu&mv=u&mvi=0&pl=23&mime=video%2Fmp4&ratebypass=yes&dur=46.347&lmt=1562006481968877&mt=1566656359&fvip=1&txp=2216222&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cmime%2Cratebypass%2Cdur%2Clmt&sig=ALgxI2wwRgIhAJB5pdvoG3qyTWJmb18a3FEUWJY2uq-z28Mg8vhMsRFtAiEAw1K0bSNtCE6gG_D6G0hi-VUXbZZ1nrGlG9Pl30Du2y4%3D&lsparams=mm%2Cmn%2Cms%2Cmv%2Cmvi%2Cpl&lsig=AHylml4wRgIhAPt8JcYyMqSVWxD4xrVh_wOzCNihP926W9JaKqIMOgfBAiEA2-zex2Ug05rFY0bKD5zUH841vafC2osneXnej9Bmr6I%3D")
        ..addListener(listener)
        ..setVolume(1.0)
        ..initialize()
        ..play();
    } else {
      if (playerController.value.isPlaying) {
        playerController.pause();
      } else {
        playerController.initialize();
        playerController.play();
      }
    }
  }

the createVideo method will create an instance and manage current playing video states.

Now, let see all the way to play a video in the Video player.

  • Play video from local asset: To play a local video in a flutter application, we have to specify the path of the video in pubspec.yaml file. After that, we can directly use the path in our application. The video player plugin comes with a special constructor which lets us build a video player controller that play a local video. By invoking this constructor we can directly call the video just by passing in the file path as a string.
    playerController = VideoPlayerController.asset(
              "assets/videos/butterfly.mp4")
            ..addListener(listener)
            ..setVolume(1.0)
            ..initialize()
            ..play();
    
  • Network Videos:  The video play controller provides a constructor to play a video from network url. As we have created an instance for connecting with cloud and play it.
    playerController = VideoPlayerController.network(
              "https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4")
            ..addListener(listener)
            ..setVolume(1.0)
            ..initialize()
            ..play();
    

  • YouTube Videos: As we know, all Youtube videos are encoded on the server, we can't directly play a Youtube video URL on any video player. So, We can get a decoded url by using the Youtube V3 API to decode these URLs into a format that we can directly play in our application. Such as, we using http://youlink.epizy.com/?url=https://www.youtube.com/watch?v=b_XZDWp9tzY&i=1 to get decoded url.
    flutter youtube url decoded list
It'll display a JSON for all the available format url that we can use anywhere to play it. As we have used in the following code snippet.

here, you can see the complete main.dart file that playing a youtube video from the above url.
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
void main() {
  runApp(Home());
}
class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primaryColor: const Color(0xFF02BB9F),
        primaryColorDark: const Color(0xFF167F67),
        accentColor: const Color(0xFF02BB9F),
      ),
      title: 'Video Example',
      home: VideoExample(),
    );
  }
}
class VideoExample extends StatefulWidget {
  @override
  VideoState createState() => VideoState();
}
class VideoState extends State<VideoExample> {
  VideoPlayerController playerController;
  VoidCallback listener;
  @override
  void initState() {
    super.initState();
    listener = () {
      setState(() {});
    };
  }
  void createVideo() {
    if (playerController == null) {
      playerController = VideoPlayerController.network(
          "https://r1---sn-aigl6nek.googlevideo.com/videoplayback?expire=1566678355&ei=80hhXeK-EJWvhAeftqiwBA&ip=185.27.134.50&id=o-ACa4cikYptSHAdpKCzCJjFMq2Gnt86FkIFLBC3wJevT2&itag=22&source=youtube&requiressl=yes&mm=31%2C29&mn=sn-aigl6nek%2Csn-aigzrn76&ms=au%2Crdu&mv=u&mvi=0&pl=23&mime=video%2Fmp4&ratebypass=yes&dur=46.347&lmt=1562006481968877&mt=1566656359&fvip=1&txp=2216222&sparams=expire%2Cei%2Cip%2Cid%2Citag%2Csource%2Crequiressl%2Cmime%2Cratebypass%2Cdur%2Clmt&sig=ALgxI2wwRgIhAJB5pdvoG3qyTWJmb18a3FEUWJY2uq-z28Mg8vhMsRFtAiEAw1K0bSNtCE6gG_D6G0hi-VUXbZZ1nrGlG9Pl30Du2y4%3D&lsparams=mm%2Cmn%2Cms%2Cmv%2Cmvi%2Cpl&lsig=AHylml4wRgIhAPt8JcYyMqSVWxD4xrVh_wOzCNihP926W9JaKqIMOgfBAiEA2-zex2Ug05rFY0bKD5zUH841vafC2osneXnej9Bmr6I%3D")
        ..addListener(listener)
        ..setVolume(1.0)
        ..initialize()
        ..play();
    } else {
      if (playerController.value.isPlaying) {
        playerController.pause();
      } else {
        playerController.initialize();
        playerController.play();
      }
    }
  }
  @override
  void deactivate() {
    playerController.setVolume(0.0);
    playerController.removeListener(listener);
    super.deactivate();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Video Example',style: TextStyle(color: Colors.white),),
      ),
      body: Center(
          child: AspectRatio(
              aspectRatio: 16 / 9,
              child: Container(
                child: (playerController != null
                    ? VideoPlayer(
                  playerController,
                )
                    : Container()),
              )
          )
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          createVideo();
          playerController.play();
        },
        child: Icon(Icons.play_arrow),
      ),
    );
  }
}

If you have followed the article carefully, you can see the app running very smoothly as shown in the above. But if you are facing any problem or you have any quires, please feel free to ask it from the comment section.
Share:

0 comments:

Post a Comment

WE'RE SOCIAL

Promotional

  • Cover art Blend

    Blend app is very advanced app there are lots of features like shayari, status, chat, feed....

Categories