Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the video player plug-in in Flutter

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to use the video player plug-in in Flutter". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to use the video player plug-in in Flutter.

Create a new video player

Before using the video player plug-in, you should add it to your pubspec.yaml file. When you open the pubspec.yaml file, you can see some of the configurations and dependencies needed to run your application. Our video player plug-in should be added under the dependencies block.

Dependencies: flutter: sdk: flutter cupertino_icons: ^ 1.0.2 video_player: 2.1.15 / / video player

The current version of the plug-in is 2.1.15, but you can add the latest version here by looking at the plug-in page. If you saved the file in VS Code, it will automatically download the plug-in. If not, open the terminal and write flutter pub get to download the plug-in.

Go to the file where you want to add the plug-in and import the video_player.dart file.

Import 'package:video_player/video_player.dart'

Now you can use the video player plug-in in your project.

There are several ways to load video. Let's load our example from the asset. Create an assets/video folder at the root layer of the project and add a video to it. Then in pubspec.yaml, in the assets section, specify the file path, as shown below.

Assets:-assets/video/video.mp4

Let's create a separate stateful widget called VideoPlayerWidget to plug in our video player related implementation.

You can initialize the video player in the initState method, as shown below. Also, don't forget to dispose and let the video player do the cleaning.

Class _ VideoPlayerState extends State {late VideoPlayerController _ videoPlayerController; @ override void initState () {super.initState (); _ videoPlayerController = VideoPlayerController.asset ('assets/video/video.mp4').. initialize (). Then ((_) {setState (() {}); _ videoPlayerController.play ();});} @ override void dispose () {_ videoPlayerController.dispose (); super.dispose () } @ override Widget build (BuildContext context) {return Center (child: VideoPlayer (_ videoPlayerController),);}}

VideoPlayerController must be specified with the late keyword, because we still don't have a video player controller defined in this line, which we'll do later. In initState, videoPlayerController has been initialized along with the path to the asset.

After initialization is complete, it changes the state and rebuilds the widget. You can start playing the video after initialization.

Instead of assets, you can use URL for video. In order to access the network, you should add Internet permissions to Android and iOS.

From the root directory, go to ios/Runner and open the info.plist file. Then, add the following configuration to the file.

NSAppTransportSecurity NSAllowsArbitraryLoads

Next, go to android/app/src/main and open AndroidManifest.xml. Then, add the following code to it.

Now you can change asset to network and add video URL there.

@ override void initState () {super.initState (); _ videoPlayerController = VideoPlayerController.network ('video_url_here').. initialize () .then ((_) {setState (() {}); _ videoPlayerController.play ();});}

Even if initialization is complete, there should be a way to display the player in the user interface. VideoPlayer widget can be used to do this. In order for it to work, you should pass the controller to VideoPlayer widget as the first parameter.

Before displaying the VideoPlayer widget, it is best to check that the initialization is successful.

@ override Widget build (BuildContext context) {return Center (child: _ videoPlayerController.value.isInitialized? VideoPlayer (_ videoPlayerController): Container (),);}

Now you can see the video on the screen. But there is one small problem: its aspect ratio is not appropriate. This can be solved by using AspectRatio widget. The video player provides an appropriate video aspect ratio, which you can use to set to AspectRatio widget.

@ override Widget build (BuildContext context) {return Center (child: _ videoPlayerController.value.isInitialized? AspectRatio (aspectRatio: _ videoPlayerController.value.aspectRatio, child: VideoPlayer (_ videoPlayerController)): Container ();}

Now you can see a video with an appropriate aspect ratio.

Add play and pause buttons

First, let's wrap the video player widget in a column widget, because we should put the play and pause buttons under the player. In the column after the player widget, let's add two ElevatedButton widgets within a Row widget, and let's add a Padding widget between the buttons to keep some breathing space.

For each ElevatedButton, add the relevant Icons as a child assembly. Then in the callback of the play button onPressed, you can refer to _ videoPlayerController and call the play method to start playing the video. In the pause button, use the pause method instead of playing.

Now you can delete the playback that you added in the initState method.

@ override Widget build (BuildContext context) {return Column (mainAxisAlignment: MainAxisAlignment.center, children: [_ videoPlayerController.value.isInitialized? AspectRatio (aspectRatio: _ videoPlayerController.value.aspectRatio, child: VideoPlayer (_ videoPlayerController)): Container (), Row (mainAxisAlignment: MainAxisAlignment.center, children: [ElevatedButton (onPressed: () {_ videoPlayerController.pause ()) }, child: Icon (Icons.pause), Padding (padding: EdgeInsets.all (2)), ElevatedButton (onPressed: () {_ videoPlayerController.play ();}, child: Icon (Icons.play_arrow))],)],);}

In addition, you can add a style to the button to get a button that looks round, usually in a video player.

@ override Widget build (BuildContext context) {return Column (mainAxisAlignment: MainAxisAlignment.center, children: [_ videoPlayerController.value.isInitialized? AspectRatio (aspectRatio: _ videoPlayerController.value.aspectRatio, child: VideoPlayer (_ videoPlayerController)): Container (), Padding (padding: EdgeInsets.all (20),), Row (mainAxisAlignment: MainAxisAlignment.center Children: [ElevatedButton (style: ButtonStyle (backgroundColor: MaterialStateProperty.all (Colors.blue), fixedSize: MaterialStateProperty.all (Size (70,70)), shape: MaterialStateProperty.all (RoundedRectangleBorder (borderRadius: BorderRadius.circular) OnPressed: () {_ videoPlayerController.pause () }, child: Icon (Icons.pause), Padding (padding: EdgeInsets.all (2)), ElevatedButton (style: ButtonStyle (backgroundColor: MaterialStateProperty.all (Colors.redAccent), fixedSize: MaterialStateProperty.all (Size (80,80) Shape: MaterialStateProperty.all (RoundedRectangleBorder (borderRadius: BorderRadius.circular)), onPressed: () {_ videoPlayerController.play () }, child: Icon (Icons.play_arrow))],)],);}

Create a fast forward

Before fast-forward, let's think about what we need. First of all, there should be a method to access the current video location / time and a method to set new values. The controller's seekTo method allows us to set the duration for the video.

You can access the current video location through the video player value property, as shown below.

ElevatedButton (style: ButtonStyle (backgroundColor: MaterialStateProperty.all (Colors.blue), fixedSize: MaterialStateProperty.all (Size (70,70)), shape: MaterialStateProperty.all (RoundedRectangleBorder (borderRadius: BorderRadius.circular (100), onPressed: () {_ videoPlayerController.seekTo (Duration (seconds: _ videoPlayerController.value.position.inSeconds + 10)) }, child: Icon (Icons.fast_forward))

Like this, when the user clicks the button, you can also reverse it by reducing it by 10 seconds.

Add a video progress indicator

The video player plug-in provides built-in functionality to add a progress bar and some controls. You can use VideoProgressIndicator widget to do this.

As the first parameter, you must pass the controller and set the allowScrubbing property. The allowScrubbing property will allow the user to slide progress by touching the widget. By enabling this, users can skip to different timestamps of the video. In addition, you can separately control the background color, buffer color and playarea color of the search bar.

VideoProgressIndicator (_ videoPlayerController, allowScrubbing: true, colors: VideoProgressColors (backgroundColor: Colors.red, bufferedColor: Colors.black, playedColor: Colors.blueAccent),)

Apply video subtitles

Subtitles require two things for your application. The first is a list of paragraphs / words from different periods, and the second is how to display these headings during video playback. To do this, there should be a way to add a listener to the time change.

The video player contains an addListener method that is executed every second. You can use this listener to provide subtitles for video players for different periods of time.

First, let's create a Map that contains time as a key and subtitle text as a value. In Map, the unit of time will be seconds.

Map captions = {5: "First subtitle", 20: "Second subtitle"}

Next, register a Listener when initializing the video player. In the callback, you can check whether the video is playing. If the video is playing, you can get the current time in seconds. Then, if the current value is included in the captions map, we can set the value to the selected title as follows.

Void initState () {super.initState (); _ videoPlayerController = VideoPlayerController.asset ('assets/video/video.mp4').. addListener () {if (_ videoPlayerController.value.isPlaying) {setState (() {if (captions.containsKey (_ videoPlayerController.value.position.inSeconds)) {selectedCaption = captions [_ videoPlayerController.value.position.inSeconds] ). Initialize () .then ((_) {setState (() {}); _ videoPlayerController.play ();});}

Now you can use ClosedCaption to set the selected title. You can add some styles to the title text for better visibility.

ClosedCaption (text: selectedCaption,textStyle: TextStyle (fontSize: 15cr color: Colors.white),)

However, every time the title changes, it is not a good idea to create the main part. Therefore, we should extract the title logic into a separate widget.

To register a listener, you should pass the video controller to a newly created widget.

From there, you can register the listener in the subassembly.

Class VCaption extends StatefulWidget {const VCaption (this.videoPlayerController,); final VideoPlayerController videoPlayerController; @ override _ VCaptionState createState () = > _ VCaptionState ();} class _ VCaptionState extends State {String? SelectedCaption = ""; Map captions = {5: "First subtitle", 20: "Second subtitle"}; @ override void initState () {widget.videoPlayerController.addListener () {if (widget.videoPlayerController.value.isPlaying) {print ("Time ${widget.videoPlayerController.value.position.inSeconds}") SetState () {if (captions.containsKey (widget.videoPlayerController.value.position.inSeconds)) {selectedCaption = captions [widget.videoPlayerController.value.position.inSeconds];}});}}); super.initState () } @ override Widget build (BuildContext context) {return ClosedCaption (text: selectedCaption,textStyle: TextStyle),);}}

Now we can add this widget to the column we created earlier and pass _ videoPlayerController as an argument. You can check to see if the video player has been initialized before adding the widget to the tree, as shown below.

_ videoPlayerController.value.isInitialized? VCaption (_ videoPlayerController): Container ()

You can use Stack widget to display these subtitles at the top of the video instead of displaying those subtitles under the video. Subtitles and progress indicators have been moved to Stack widget for display at the top of the video.

Stack (children: [_ videoPlayerController.value.isInitialized? AspectRatio (aspectRatio: _ videoPlayerController.value.aspectRatio, child: VideoPlayer (_ videoPlayerController)): Container (), Positioned (bottom: 2, width: MediaQuery.of (context). Size.width, child: _ videoPlayerController.value.isInitialized? VCaption (_ videoPlayerController): Container (),), Positioned (bottom: 0, width: MediaQuery.of (context). Size.width, child: VideoProgressIndicator (_ videoPlayerController, allowScrubbing: false Colors: VideoProgressColors (backgroundColor: Colors.blueGrey, bufferedColor: Colors.blueGrey, playedColor: Colors.blueAccent)],)

Thank you for reading, the above is the content of "how to use the video player plug-in in Flutter". After the study of this article, I believe you have a deeper understanding of how to use the video player plug-in in Flutter. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report