在任何应用开发中,视频播放都是一项常见任务,Flutter 应用也不例外。为了支持视频播放,Flutter团队提供了 video_player 插件。你可以使用 video_player 插件播放存储在本地文件系统中的视频或者网络视频。
在 iOS 上,video_player 使用 AVPlayer 进行播放控制。在 Android 上,使用的是 ExoPlayer。
这个章节讲解的是如何借助 video_player 包接收网络视频流,并加入基本的播放、暂停操作。
步骤
添加
video_player依赖添加权限
创建并初始化
VideoPlayerController展示视频播放器
播放视频和暂停视频
1. 添加 video_player 依赖
这个章节基于一个 Flutter 插件: video_player。首先,添加依赖到 pubspec.yaml 中。
dependencies:flutter:sdk: fluttervideo_player:
2. 添加权限
然后,你需要确保你的应用拥有从网络中获取视频流的权限。因此,你需要更新你的 android 和 ios 配置。
Android 配置
在 AndroidManifest.xml 文件中的 <application> 配置项下加入如下权限。AndroidManifest.xml 文件的路径是 <projectroot>/android/app/src/main/AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"><application ...></application><uses-permission android:name="android.permission.INTERNET"/></manifest>
iOS 配置
针对 iOS,你需要在 <project root>/ios/Runner/Info.plist 路径下的 Info.plist 文件中加入如下配置。
<key>NSAppTransportSecurity</key><dict><key>NSAllowsArbitraryLoads</key><true/></dict>
请注意::The video_player plugin does not work on iOS simulators. You must test videos on real iOS devices.
video_player 插件在 iOS 模拟器上不能使用,必须要在 iOS 真机上进行测试。
3. 创建并初始化 VideoPlayerController
video_player 插件成功安装且权限设置完成后,需要创建一个 VideoPlayerController。VideoPlayerController 类允许你播放不同类型的视频并进行播放控制。
在播放视频前,需要对播放控制器进行初始化。初始化过程主要是与视频源建立连接和播放控制的准备。
创建和初始化 VideoPlayerController 时,请遵循以下步骤:
- Create a
StatefulWidgetwith a companionStateclass
创建一个 `StatefulWidget` 组件和 `State` 类
在
State类中增加一个变量来存放VideoPlayerController在
State累中增加另外一个变量来存放VideoPlayerController.initialize返回的Future在
initState方法里创建和初始化控制器在
dispose方法里销毁控制器
class VideoPlayerScreen extends StatefulWidget {VideoPlayerScreen({Key key}) : super(key: key);@override_VideoPlayerScreenState createState() => _VideoPlayerScreenState();}class _VideoPlayerScreenState extends State<VideoPlayerScreen> {VideoPlayerController _controller;Future<void> _initializeVideoPlayerFuture;@overridevoid initState() {// Create an store the VideoPlayerController. The VideoPlayerController// offers several different constructors to play videos from assets, files,// or the internet._controller = VideoPlayerController.network('https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4',);_initializeVideoPlayerFuture = _controller.initialize();super.initState();}@overridevoid dispose() {// Ensure you dispose the VideoPlayerController to free up resources_controller.dispose();super.dispose();}@overrideWidget build(BuildContext context) {// Show the video in the next step}}
4. 展示视频播放器
现在到了展示播放器的时候。video_player 插件提供了 VideoPlayer 组件来展示已经被 VideoPlayerController 初始化完成的视频。默认情况下,VideoPlayer 组件会尽可能撑满整个空间。但是这通常不会太理想,因为很多时候视频需要在特定的宽高比下展示,比如 16x9 或者 4x3。
因此,你可以把 VideoPlayer 组件嵌进一个 AspectRatio 组件中,保证视频播放保持正确的比例。
此外,你必须在 _initializeVideoPlayerFuture 完成后才展示 VideoPlayer 组件。你可以使用 FutureBuilder 来展示一个旋转的加载图标直到初始化完成。请注意:控制器初始化完成并不会立即开始播放。
// Use a FutureBuilder to display a loading spinner while you wait for the// VideoPlayerController to finish initializing.FutureBuilder(future: _initializeVideoPlayerFuture,builder: (context, snapshot) {if (snapshot.connectionState == ConnectionState.done) {// If the VideoPlayerController has finished initialization, use// the data it provides to limit the Aspect Ratio of the VideoPlayerreturn AspectRatio(aspectRatio: _controller.value.aspectRatio,// Use the VideoPlayer widget to display the videochild: VideoPlayer(_controller),);} else {// If the VideoPlayerController is still initializing, show a// loading spinnerreturn Center(child: CircularProgressIndicator());}},)
5. 播放视频和暂停视频
默认情况下,播放器启动时会处于暂停状态。开始播放,需要调用 VideoPlayerController 提供的 play 方法。停止播放,需要调用pause 方法。
在这个示例中,向应用加入了一个 FloatingActionButton,这个按钮会根据播放状态展示播放或者暂停的图标。当用户点击按钮,会切换播放状态。如果当前是暂停状态,就开始播放。如果当前是播放状态,就暂停播放。
FloatingActionButton(onPressed: () {// Wrap the play or pause in a call to `setState`. This ensures the correct// icon is shownsetState(() {// If the video is playing, pause it.if (_controller.value.isPlaying) {_controller.pause();} else {// If the video is paused, play it_controller.play();}});},// Display the correct icon depending on the state of the player.child: Icon(_controller.value.isPlaying ? Icons.pause : Icons.play_arrow,),)
完整示例
import 'dart:async';import 'package:flutter/material.dart';import 'package:video_player/video_player.dart';void main() => runApp(VideoPlayerApp());class VideoPlayerApp extends StatelessWidget {@overrideWidget build(BuildContext context) {return MaterialApp(title: 'Video Player Demo',home: VideoPlayerScreen(),);}}class VideoPlayerScreen extends StatefulWidget {VideoPlayerScreen({Key key}) : super(key: key);@override_VideoPlayerScreenState createState() => _VideoPlayerScreenState();}class _VideoPlayerScreenState extends State<VideoPlayerScreen> {VideoPlayerController _controller;Future<void> _initializeVideoPlayerFuture;@overridevoid initState() {// Create and store the VideoPlayerController. The VideoPlayerController// offers several different constructors to play videos from assets, files,// or the internet._controller = VideoPlayerController.network('https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4',);// Initialize the controller and store the Future for later use_initializeVideoPlayerFuture = _controller.initialize();// Use the controller to loop the video_controller.setLooping(true);super.initState();}@overridevoid dispose() {// Ensure you dispose the VideoPlayerController to free up resources_controller.dispose();super.dispose();}@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: Text('Butterfly Video'),),// Use a FutureBuilder to display a loading spinner while you wait for the// VideoPlayerController to finish initializing.body: FutureBuilder(future: _initializeVideoPlayerFuture,builder: (context, snapshot) {if (snapshot.connectionState == ConnectionState.done) {// If the VideoPlayerController has finished initialization, use// the data it provides to limit the Aspect Ratio of the Videoreturn AspectRatio(aspectRatio: _controller.value.aspectRatio,// Use the VideoPlayer widget to display the videochild: VideoPlayer(_controller),);} else {// If the VideoPlayerController is still initializing, show a// loading spinnerreturn Center(child: CircularProgressIndicator());}},),floatingActionButton: FloatingActionButton(onPressed: () {// Wrap the play or pause in a call to `setState`. This ensures the// correct icon is shownsetState(() {// If the video is playing, pause it.if (_controller.value.isPlaying) {_controller.pause();} else {// If the video is paused, play it_controller.play();}});},// Display the correct icon depending on the state of the player.child: Icon(_controller.value.isPlaying ? Icons.pause : Icons.play_arrow,),), // This trailing comma makes auto-formatting nicer for build methods.);}}