flutter series: using media player in flutter

Introduction

Today's apps are becoming more and more powerful. In addition to basic graphics and text, they also require a variety of other functions, such as videos and live broadcasts.

Live streaming may be more complicated because it involves pulling and pushing streams, which requires server-side support, but video playback is relatively simple. So how to use a media player in Flutter?

Let’s take a look.

Preparation before use

Flutter itself does not support the media playback function. In order to implement this function, we need to use an additional third-party plug-in called video_player.

First we need to add video_player to the flutter application. It is very simple to add, just execute the following command:

flutter pub add video_player 

This command will add the following content to pubspec.xml:

dependencies:
  flutter:
    sdk: flutter

  video_player: ^2.4.7

After adding the dependency package, we also need to add corresponding permissions to the application. Make sure you can use the permissions for audio and video playback.

If it is in android, you need to add content similar to the following to the AndroidManifest.xml file:

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application ...>

    </application>

    <uses-permission android:name="android.permission.INTERNET"/>
</manifest>

In IOS, you need to add the following content to Info.plist:

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

Using video_player in flutter

The class related to video playback in video_player is called VideoPlayerController. In IOS, the bottom layer is AVPlayer, and in Android, the bottom layer is ExoPlayer.

VideoPlayerController has several construction methods, let's take a look.

  VideoPlayerController.asset

The asset method indicates that the video is obtained from the application's asset.

 VideoPlayerController.network

The network method indicates that the video is obtained from the network.

  VideoPlayerController.file

The file method indicates that the video is obtained through the format of 'file://${file.path}'.

There is also a method only used in andorid, which means loading video from contentUri:

  VideoPlayerController.contentUri

For the sake of simplicity, here we choose a science and education video on NetEase as the video to be played.

Then we can build this controller through the VideoPlayerController.network method:

    videoPlayerController = VideoPlayerController.network(
      'https://flv.bn.netease.com/1c04bfd72901f0661b486465e09cfdc01754c20db0686786f4e20a5f7d271ba0de6c1177a0da1c4c2d7c367e20ee16d4a90ac7ff4ea664820ba1b401f3e53f135f72cdff855e78ca5fb7849fb6ff7ccb9de1613ad3bfc59db83493b5f18a0a27f15048df6585361cd67c3b37551e10981c40dcdfdb77b7e6.mp4',
    );

Before using video, you need to perform initial operations. Initialization is to call its initialize method. The function of this method is to open the given data source and load its metadata.

Because the initialize method is a time-consuming operation, the return type of this method is Future:

  Future<void> initialize() async {

We can use it like this:

late Future<void> playerFuture;
playerFuture = videoPlayerController.initialize();

With the player's Future, we can use it with the FutureBuilder in flutter:

body: FutureBuilder(
        future: playerFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return AspectRatio(
              aspectRatio: videoPlayerController.value.aspectRatio,
              child: VideoPlayer(videoPlayerController),
            );
          } else {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
        },
      ),

In FutureBuilder, we determine whether the video has been loaded by judging the connectionState. If it has not been loaded, we use CircularProgressIndicator to indicate that it is loading.

If loading is complete, just display the VideoPlayer component directly.

Because different videos have different aspect ratios, in order to perfectly display the loaded video on the flutter interface, we encapsulate VideoPlayer in an AspectRatio component.

Finally, we have to add a control device to control the pause and playback of the video:

floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            if (videoPlayerController.value.isPlaying) {
              videoPlayerController.pause();
            } else {
              videoPlayerController.play();
            }
          });
        },
        child: Icon(
          videoPlayerController.value.isPlaying ? Icons.pause : Icons.play_arrow,
        ),
      )

Here, videoPlayerController.value.isPlaying is used to determine whether the video is playing, and setState is called in the onPressed method to call the videoPlayerController.pause or videoPlayerController.play method.

Summarize

Such an app that can play external videos is ready. After running, its interface will look like this:

You can expand on the basis of this player, and your own video APP will be completed.

Examples in this article:https://github.com/ddean2009/learn-flutter.git

Supongo que te gusta

Origin blog.csdn.net/superfjj/article/details/129818918
Recomendado
Clasificación