Flutter视频播放器插件theoplayer的使用

发布于 1周前 作者 vueper 来自 Flutter

Flutter视频播放器插件theoplayer的使用

概述

theoplayer 插件为 Flutter 应用提供了一个 THEOplayer 组件,支持在以下平台上进行视频播放:

  • Android, Android TV & FireTV
  • iOS
  • HTML5 (web, mobile web)

本文档将介绍如何创建一个包含 THEOplayer 组件的最小应用程序,并概述附带的示例应用程序。

先决条件

要使用 THEOplayer SDK,需要从对应的平台获取有效的 THEOplayer 许可证。你可以通过 THEOplayer 门户 获取许可证。

如果你没有 Flutter 的基础,建议先查看 Flutter 文档

使用指南

这些指南介绍了如何在你的 Flutter 项目中使用 THEOplayer Flutter SDK,可以线性阅读或直接查找特定部分。建议你对 Flutter 有一定的了解,以便更高效地使用 THEOplayer Flutter SDK。

特性

THEOplayer 支持不同的平台功能,具体特性如下表所示:

Feature Android, Android TV, Fire TV Web iOS, tvOS
Streaming MPEG-DASH (fmp4, CMAF), HLS (TS, CMAF), Progressive MP4, MP3 MPEG-DASH (fmp4, CMAF), HLS (TS, CMAF), Progressive MP4, MP3 HLS (TS, CMAF), Progressive MP4, MP3
Content Protection Widevine Widevine, Fairplay Fairplay
DRM Connectors Through hooking into native implementation… check guides! Through hooking into native implementation… check guides! Through hooking into native implementation… check guides!
Subtitles & Closed Captions In-stream subtitles supported by the platform. Note: If you use Texture-based rendering on Android, you need to implement the subtitle rendering based on track events. In-stream subtitles supported by the platform. Note: If you use Texture-based rendering on Android, you need to implement the subtitle rendering based on track events. In-stream subtitles supported by the platform. Note: If you use Texture-based rendering on Android, you need to implement the subtitle rendering based on track events.

更多详细信息请参见官方文档。

开始使用

创建一个最小的应用程序

以下是创建一个最小的 THEOplayer Flutter 应用程序的步骤和示例代码:

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:theoplayer/theoplayer.dart';

const PLAYER_LICENSE = "YOUR_LICENSE_KEY_HERE";

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

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

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late THEOplayer player;

  final _messengerKey = GlobalKey<ScaffoldMessengerState>();

  @override
  void initState() {
    super.initState();

    player = THEOplayer(
      theoPlayerConfig: THEOplayerConfig(
        license: PLAYER_LICENSE,
      ),
      onCreate: () {
        print("main - THEOplayer - onCreate");
        player.autoplay = true;
        player.allowBackgroundPlayback = true;
        player.allowAutomaticPictureInPicture = true;

        player.addEventListener(PlayerEventTypes.ERROR, (errorEvent) {
          var error = errorEvent as ErrorEvent;
          _messengerKey.currentState?.showSnackBar(
            SnackBar(
              duration: const Duration(milliseconds: 6000),
              backgroundColor: Colors.red,
              content: Text(error.error),
              action: SnackBarAction(
                label: 'OK',
                onPressed: () {},
              ),
            ),
          );
        });
      },
    );
  }

  @override
  void dispose() {
    player.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      scaffoldMessengerKey: _messengerKey,
      home: Scaffold(
        appBar: AppBar(
          title: const Text('THEOplayer example app'),
        ),
        body: Center(
          child: SizedBox(
            width: 400,
            height: 300,
            child: Stack(
              alignment: Alignment.center,
              children: [
                AspectRatio(
                  aspectRatio: 16 / 9,
                  child: THEOplayerView(player: player),
                ),
                PlayerUI(player: player),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class PlayerUI extends StatelessWidget {
  final THEOplayer player;

  PlayerUI({required this.player});

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        Row(
          mainAxisSize: MainAxisSize.max,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () => {player.play()},
              child: const Text("PLAY"),
            ),
            ElevatedButton(
              onPressed: () => {player.pause()},
              child: const Text("PAUSE"),
            ),
          ],
        ),
      ],
    );
  }
}

设置播放源

player.source = SourceDescription(sources: [
  TypedSource(src: "https://cdn.theoplayer.com/video/big_buck_bunny/big_buck_bunny.m3u8"),
]);

处理错误

player.addEventListener(PlayerEventTypes.ERROR, (errorEvent) {
  var error = errorEvent as ErrorEvent;
  _messengerKey.currentState?.showSnackBar(
    SnackBar(
      duration: const Duration(milliseconds: 6000),
      backgroundColor: Colors.red,
      content: Text(error.error),
      action: SnackBarAction(
        label: 'OK',
        onPressed: () {},
      ),
    ),
  );
});

全屏模式

player.setPresentationMode(PresentationMode.FULLSCREEN);

画中画模式

if (kIsWeb) {
  player.setPresentationMode(PresentationMode.PIP);
} else {
  player.allowAutomaticPictureInPicture = !player.allowAutomaticPictureInPicture;
}

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

1 回复

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


当然,以下是如何在Flutter项目中使用theoplayer插件来实现视频播放的一个基本示例。theoplayer是一个功能强大的视频播放器插件,支持多种格式和高级功能。

首先,确保你已经在pubspec.yaml文件中添加了theoplayer依赖:

dependencies:
  flutter:
    sdk: flutter
  theoplayer: ^x.y.z  # 请替换为最新版本号

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

接下来,我们创建一个简单的Flutter应用来展示如何使用theoplayer

main.dart

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'TheoPlayer Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: VideoPlayerScreen(),
    );
  }
}

class VideoPlayerScreen extends StatefulWidget {
  @override
  _VideoPlayerScreenState createState() => _VideoPlayerScreenState();
}

class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
  TheoPlayerController? _controller;

  @override
  void initState() {
    super.initState();
    // 初始化TheoPlayerController
    _controller = TheoPlayerController(
      dataSource: TheoDataSource.network(
        'https://www.example.com/path/to/your/video.mp4', // 替换为你的视频URL
        headers: <String, String>{
          'Authorization': 'Bearer YOUR_ACCESS_TOKEN', // 如果需要身份验证,请添加相应的headers
        },
      ),
      autoPlay: true, // 自动播放
      muted: false, // 是否静音
      aspectRatio: 16 / 9, // 视频宽高比
    );

    // 监听播放结束事件
    _controller!.onEnded.listen((_) {
      print('Video playback finished.');
    });
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('TheoPlayer Demo'),
      ),
      body: Center(
        child: _controller != null
            ? TheoPlayer(
                controller: _controller!,
              )
            : CircularProgressIndicator(),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // 示例:控制播放
          if (_controller!.value.isPlaying) {
            _controller!.pause();
          } else {
            _controller!.play();
          }
        },
        tooltip: _controller!.value.isPlaying ? 'Pause' : 'Play',
        child: Icon(
          _controller!.value.isPlaying ? Icons.pause : Icons.play_arrow,
        ),
      ),
    );
  }
}

解释

  1. 依赖安装:首先,在pubspec.yaml文件中添加theoplayer依赖。

  2. 状态管理:创建一个_VideoPlayerScreenState类来管理视频播放器的状态。

  3. 初始化控制器:在initState方法中,初始化TheoPlayerController,并设置视频源、自动播放、静音和宽高比等参数。

  4. 事件监听:通过_controller!.onEnded.listen方法监听视频播放结束事件。

  5. 释放资源:在dispose方法中释放TheoPlayerController,以避免内存泄漏。

  6. UI构建:使用TheoPlayer小部件来显示视频播放器,并使用FloatingActionButton来控制播放和暂停。

  7. 加载指示器:在控制器初始化之前显示一个CircularProgressIndicator作为加载指示器。

你可以根据需要进一步自定义和扩展这个示例,比如添加更多控制按钮(如音量控制、全屏切换等),或处理更多事件(如缓冲、错误处理等)。

希望这个示例能帮助你在Flutter项目中成功集成theoplayer插件!

回到顶部