Flutter视频播放插件ezplayer的使用

Flutter视频播放插件ezplayer的使用

支持平台

Android, iOS, MacOS, Windows, Linux

安装

我们使用了 flutter_base_player,并且它有一些额外的配置步骤,请参考这些包提供的说明文档。

示例

以下是一个完整的示例代码,展示如何在 Flutter 中使用 ezplayer 插件来播放视频。

import 'package:flutter/material.dart';
import 'package:ezplayer/ezplayer.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  FlutterBasePlayer player = FlutterBasePlayer();

  BoxFit fit = BoxFit.contain;
  double ratio = 4 / 3;

  @override
  void initState() {
    player.loadNetwork('https://media.w3.org/2010/05/sintel/trailer.mp4');
    // player.loadNetwork('http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4');
    player.play();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: ListView(
        children: [
          const Center(
            child: Text(
              'Video Test',
              style: TextStyle(fontSize: 24, height: 2),
            ),
          ),
          SizedBox(
            height: 300,
            width: 300,
            child: player.builder(context, fit: fit,),
            // child: player.builder(context, fit: fit, ratio: ratio),
          ),
          const SizedBox(height: 30),
          Wrap(
            spacing: 20,
            runSpacing: 10,
            children: [
              TextButton(onPressed: player.play, child: const Text('play')),
              TextButton(onPressed: player.pause, child: const Text('pause')),
              TextButton(
                onPressed: () {
                  setState(() {
                    fit = BoxFit.contain;
                  });
                },
                child: const Text('contain'),
              ),
              TextButton(
                onPressed: () {
                  setState(() {
                    fit = BoxFit.cover;
                  });
                },
                child: const Text('cover'),
              ),
              TextButton(
                onPressed: () {
                  setState(() {
                    fit = BoxFit.fill;
                  });
                },
                child: const Text('fill'),
              ),
              TextButton(
                onPressed: () {
                  player.seek(const Duration(seconds: 10));
                },
                child: const Text('seek to 10s'),
              ),
              TextButton(
                onPressed: () {
                  player.seek(const Duration(seconds: 20));
                },
                child: const Text('seek to 20s'),
              ),
              TextButton(
                onPressed: () {
                  player.seek(const Duration(seconds: 30));
                },
                child: const Text('seek to 30s'),
              ),
              TextButton(
                onPressed: () {
                  player.seek(const Duration(seconds: 40));
                },
                child: const Text('seek to 40s'),
              ),
              TextButton(
                onPressed: () {
                  player.seek(const Duration(seconds: 50));
                },
                child: const Text('seek to 50s'),
              ),
              TextButton(
                onPressed: () {
                  player.setLooping(true);
                },
                child: const Text('setLooping true'),
              ),
              TextButton(
                onPressed: () {
                  player.setLooping(false);
                },
                child: const Text('setLooping false'),
              ),
              TextButton(
                onPressed: () {
                  player.setPlaybackSpeed(1.0);
                },
                child: const Text('setPlaybackSpeed 1.0'),
              ),
              TextButton(
                onPressed: () {
                  player.setPlaybackSpeed(0.5);
                },
                child: const Text('setPlaybackSpeed 0.5'),
              ),
              TextButton(
                onPressed: () {
                  player.setPlaybackSpeed(2.0);
                },
                child: const Text('setPlaybackSpeed 2.0'),
              ),
              TextButton(
                onPressed: () {
                  player.setVolume(1.0);
                },
                child: const Text('setVolume 1.0'),
              ),
              TextButton(
                onPressed: () {
                  player.setVolume(0.8);
                },
                child: const Text('setVolume 0.8'),
              ),
              TextButton(
                onPressed: () {
                  player.setVolume(0.6);
                },
                child: const Text('setVolume 0.6'),
              ),
              TextButton(
                onPressed: () {
                  player.setVolume(0.0);
                },
                child: const Text('setVolume 0.0'),
              ),
            ],
          ),
          const SizedBox(height: 30),
          const Text('initial state:'),
          Wrap(
              spacing: 30,
              runSpacing: 10,
              alignment: WrapAlignment.start,
              children: [
                Text('position: ${player.position}'),
                Text('duration: ${player.duration}'),
                Text('aspectRatio: ${player.aspectRatio}'),
                Text('isPlaying: ${player.isPlaying}'),
                
                Text('playbackSpeed: ${player.playbackSpeed}'),
                Text('size: ${player.size}'),
                Text('volume: ${player.volume}'),

                Text('errorMessage: ${player.errorMessage}'),
                Text('hasError: ${player.hasError}'),

                Text('isBuffering: ${player.isBuffering}'),
                Text('isInitialized: ${player.isInitialized}'),
                Text('isLooping: ${player.isLooping}'),
              ],
          ),
          const SizedBox(height: 30),
          const Text('real-time state:'),
          ChangeNotifierBuilder(
            notifier: player.eventStream,
            builder: (context) {
              return Wrap(
                spacing: 30,
                runSpacing: 10,
                children: [
                  Text('position: ${player.position}'),
                  Text('duration: ${player.duration}'),
                  Text('aspectRatio: ${player.aspectRatio}'),
                  Text('isPlaying: ${player.isPlaying}'),
                  
                  Text('playbackSpeed: ${player.playbackSpeed}'),
                  Text('size: ${player.size}'),
                  Text('volume: ${player.volume}'),

                  Text('errorMessage: ${player.errorMessage}'),
                  Text('hasError: ${player.hasError}'),

                  Text('isBuffering: ${player.isBuffering}'),
                  Text('isInitialized: ${player.isInitialized}'),
                  Text('isLooping: ${player.isLooping}'),
                ],
              );
            }
          )
          
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          player.play();
        },
        child: const Icon(Icons.play_circle),
      ),
    );
  }
}

说明

  • 初始化:在 initState 方法中调用 player.loadNetwork() 加载网络视频。
  • 控制按钮:提供了多个按钮用于播放、暂停、调整播放速度、设置音量等操作。
  • 状态更新:通过 ChangeNotifierBuilder 实时更新视频播放的状态信息。

注意事项

  • 确保已正确安装 ezplayer 插件,并在 pubspec.yaml 文件中添加依赖:
    dependencies:
      ezplayer: ^版本号
    

更多关于Flutter视频播放插件ezplayer的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter视频播放插件ezplayer的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


ezplayer 是一个功能强大的 Flutter 视频播放插件,支持多种视频格式和播放控制功能。它提供了丰富的 API,可以轻松集成到 Flutter 应用中。以下是如何使用 ezplayer 插件的步骤:

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 ezplayer 依赖:

dependencies:
  flutter:
    sdk: flutter
  ezplayer: ^0.0.1 # 请使用最新版本

然后运行 flutter pub get 来安装依赖。

2. 导入插件

在需要使用 ezplayer 的 Dart 文件中导入插件:

import 'package:ezplayer/ezplayer.dart';

3. 创建并配置 EzPlayer

你可以通过创建一个 EzPlayer 实例并将其添加到你的 UI 中来使用它。

class VideoPlayerScreen extends StatefulWidget {
  [@override](/user/override)
  _VideoPlayerScreenState createState() => _VideoPlayerScreenState();
}

class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
  late EzPlayer _ezPlayer;

  [@override](/user/override)
  void initState() {
    super.initState();
    _ezPlayer = EzPlayer()
      ..setDataSource(
        "https://www.sample-videos.com/video123/mp4/720/big_buck_bunny_720p_20mb.mp4",
        autoPlay: true,
      );
  }

  [@override](/user/override)
  void dispose() {
    _ezPlayer.dispose();
    super.dispose();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Video Player'),
      ),
      body: Center(
        child: _ezPlayer,
      ),
    );
  }
}

4. 配置播放器

EzPlayer 提供了多种配置选项,你可以根据需要进行设置:

  • 自动播放:通过 autoPlay 参数设置是否自动播放。
  • 循环播放:通过 loop 参数设置是否循环播放。
  • 全屏控制:通过 allowFullScreen 参数设置是否允许全屏播放。
  • 播放速度:通过 playbackSpeed 参数设置播放速度。
_ezPlayer.setDataSource(
  "https://www.sample-videos.com/video123/mp4/720/big_buck_bunny_720p_20mb.mp4",
  autoPlay: true,
  loop: false,
  allowFullScreen: true,
  playbackSpeed: 1.0,
);

5. 播放控制

EzPlayer 提供了多种播放控制方法,例如:

  • 播放_ezPlayer.play()
  • 暂停_ezPlayer.pause()
  • 停止_ezPlayer.stop()
  • 跳转到指定位置_ezPlayer.seekTo(Duration(seconds: 10))

你可以根据需要调用这些方法来控制视频播放。

6. 处理播放状态

你可以监听播放器的状态变化,例如播放、暂停、完成等:

_ezPlayer.onPlayerStateChanged.listen((state) {
  if (state == PlayerState.PLAYING) {
    print("视频正在播放");
  } else if (state == PlayerState.PAUSED) {
    print("视频已暂停");
  } else if (state == PlayerState.COMPLETED) {
    print("视频播放完成");
  }
});

7. 全屏播放

EzPlayer 支持全屏播放,你可以通过设置 allowFullScreen 参数来启用全屏功能。用户可以通过点击全屏按钮进入全屏模式。

8. 自定义 UI

EzPlayer 提供了默认的播放器 UI,但你可以根据需要自定义 UI。你可以通过 EzPlayer 的 API 来控制播放器,并构建你自己的 UI。

9. 处理播放错误

你可以监听播放器的错误事件,并处理播放过程中可能出现的错误:

_ezPlayer.onError.listen((error) {
  print("播放错误: $error");
});

10. 释放资源

在页面销毁时,记得释放播放器资源,以防止内存泄漏:

[@override](/user/override)
void dispose() {
  _ezPlayer.dispose();
  super.dispose();
}
回到顶部