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

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

简介

cached_chewie_plus 是官方 chewie 插件的一个分支,捆绑了 flutter_cached_video_player_plus。它提供了一个功能强大的视频播放器,支持缓存、字幕、自定义选项等功能。

安装

在您的 Flutter 项目的 pubspec.yaml 文件中添加 cached_chewie_plus 依赖:

dependencies:
  cached_chewie_plus: <latest_version>

请确保将 <latest_version> 替换为最新版本号。

使用方法

基本用法

首先,您需要导入 cached_chewie_plus 包,并创建一个 CachedVideoPlayerController 来控制视频播放:

extension UriString on String {
  Uri get toUri => Uri.parse(this);
}

import 'package:cached_chewie_plus/cached_chewie_plus.dart';

final videoPlayerController = CachedVideoPlayerController.networkUrl(
    'https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4'.toUri);

await videoPlayerController.initialize();

final chewieController = ChewieController(
  videoPlayerController: videoPlayerController,
  autoPlay: true,
  looping: true,
);

final playerWidget = Chewie(
  controller: chewieController,
);

资源释放

为了防止内存泄漏,请确保在不再使用控制器时释放它们。可以通过重写 StatefulWidgetdispose 方法来实现:

@override
void dispose() {
  videoPlayerController.dispose();
  chewieController.dispose();
  super.dispose();
}

配置选项

Chewie 提供了一些控制视频的选项,默认情况下这些选项会显示在一个 showModalBottomSheet 中(类似于 YouTube)。默认情况下,Chewie 会传递“播放速度”和“字幕”选项作为 OptionItem

您可以向 ChewieController 添加其他选项:

additionalOptions: (context) {
  return <OptionItem>[
    OptionItem(
      onTap: () => debugPrint('My option works!'),
      iconData: Icons.chat,
      title: 'My localized title',
    ),
    OptionItem(
      onTap: () =>
          debugPrint('Another option that works!'),
      iconData: Icons.chat,
      title: 'Another localized title',
    ),
  ];
},

自定义选项弹出窗口

如果您不喜欢默认的 showModalBottomSheet 显示方式,可以使用 optionsBuilder 方法覆盖视图:

optionsBuilder: (context, defaultOptions) async {
  await showDialog<void>(
    context: context,
    builder: (ctx) {
      return AlertDialog(
        content: ListView.builder(
          itemCount: defaultOptions.length,
          itemBuilder: (_, i) => ActionChip(
            label: Text(defaultOptions[i].title),
            onPressed: () =>
                defaultOptions[i].onTap!(),
          ),
        ),
      );
    },
  );
},

国际化

为了支持多语言,您可以添加翻译字符串:

optionsTranslation: OptionsTranslation(
  playbackSpeedButtonText: 'Wiedergabegeschwindigkeit',
  subtitlesButtonText: 'Untertitel',
  cancelButtonText: 'Abbrechen',
),

字幕支持

从 1.1.0 版本开始,chewie 支持字幕。以下是如何使用字幕的示例:

ChewieController(
  videoPlayerController: _videoPlayerController,
  autoPlay: true,
  looping: true,
  subtitle: Subtitles([
    Subtitle(
      index: 0,
      start: Duration.zero,
      end: const Duration(seconds: 10),
      text: 'Hello from subtitles',
    ),
    Subtitle(
      index: 1,
      start: const Duration(seconds: 10),
      end: const Duration(seconds: 20),
      text: 'Whats up? :)',
    ),
  ]),
  subtitleBuilder: (context, subtitle) => Container(
    padding: const EdgeInsets.all(10.0),
    child: Text(
      subtitle,
      style: const TextStyle(color: Colors.white),
    ),
  ),
);

示例代码

以下是一个完整的示例代码,展示如何在 Flutter 应用程序中使用 cached_chewie_plus

import 'package:flutter/material.dart';
import 'package:cached_chewie_plus/cached_chewie_plus.dart';
import 'dart:core';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

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

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

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late final CachedVideoPlayerController _videoPlayerController;
  late final ChewieController _chewieController;

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

    _videoPlayerController = CachedVideoPlayerController.networkUrl(
        'https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4'.toUri);

    _videoPlayerController.initialize().then((_) {
      setState(() {});
    });

    _chewieController = ChewieController(
      videoPlayerController: _videoPlayerController,
      autoPlay: true,
      looping: true,
      subtitle: Subtitles([
        Subtitle(
          index: 0,
          start: Duration.zero,
          end: const Duration(seconds: 10),
          text: 'Hello from subtitles',
        ),
        Subtitle(
          index: 1,
          start: const Duration(seconds: 10),
          end: const Duration(seconds: 20),
          text: 'Whats up? :)',
        ),
      ]),
      subtitleBuilder: (context, subtitle) => Container(
        padding: const EdgeInsets.all(10.0),
        child: Text(
          subtitle,
          style: const TextStyle(color: Colors.white),
        ),
      ),
    );
  }

  @override
  void dispose() {
    _videoPlayerController.dispose();
    _chewieController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: _videoPlayerController.value.isInitialized
            ? Chewie(
                controller: _chewieController,
              )
            : const CircularProgressIndicator(),
      ),
    );
  }
}

iOS 注意事项

video_player 插件在 iOS 模拟器上仅在 Flutter 1.26.0 及以上版本中工作。如果遇到问题,您可以切换到 beta 渠道:

flutter channel beta

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

1 回复

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


当然,以下是一个关于如何使用 cached_chewie_plus 插件在 Flutter 中实现视频播放器的代码示例。cached_chewie_plus 是一个功能强大的 Flutter 视频播放器插件,它结合了 chewievideo_player 插件,并添加了视频缓存功能。

首先,确保在你的 pubspec.yaml 文件中添加以下依赖项:

dependencies:
  flutter:
    sdk: flutter
  video_player: ^2.2.17  # 请检查最新版本号
  chewie: ^1.2.2  # 请检查最新版本号
  cached_network_image: ^3.1.0  # cached_chewie_plus 依赖的库
  cached_chewie_plus: ^0.1.0  # 请检查最新版本号

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

接下来,创建一个 Flutter 页面来使用 cached_chewie_plus 插件。以下是一个完整的示例代码:

import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
import 'package:chewie/chewie.dart';
import 'package:cached_chewie_plus/cached_chewie_plus.dart';
import 'package:provider/provider.dart';

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

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

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

class _VideoPlayerScreenState extends State<VideoPlayerScreen> {
  late VideoPlayerController _controller;
  ChewieController? _chewieController;

  @override
  void initState() {
    super.initState();
    // 使用网络视频URL初始化 VideoPlayerController
    _controller = VideoPlayerController.network(
      'https://www.example.com/video.mp4',
    )..initialize().then((_) {
      // 一旦视频初始化完成,设置 ChewieController
      setState(() {
        _chewieController = ChewieController(
          videoPlayerController: _controller,
          aspectRatio: _controller.value.aspectRatio,
          autoPlay: false,
          looping: false,
          // 使用 CachedChewiePlus 配置
          cachedChewieConfigProvider: CachedChewieConfigProvider(
            useCache: true,
            cacheDirectory: 'my_video_cache',
            maxCacheSize: 1024 * 1024 * 100, // 100 MB
          ),
        );
      });
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Video Player Demo'),
      ),
      body: Center(
        child: _chewieController != null
            ? CachedChewiePlus(
                controller: _chewieController!,
              )
            : CircularProgressIndicator(),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            _controller.value.isPlaying
                ? _controller.pause()
                : _controller.play();
          });
        },
        child: Icon(
          _controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
        ),
      ),
    );
  }
}

代码解释:

  1. 依赖项:在 pubspec.yaml 中添加了 video_player, chewie, cached_network_image, 和 cached_chewie_plus
  2. 初始化:在 initState 方法中,使用视频的网络 URL 初始化 VideoPlayerController。一旦视频初始化完成,创建一个 ChewieController 并将其与 VideoPlayerController 关联。
  3. CachedChewiePlus:在 ChewieController 中使用 CachedChewieConfigProvider 配置缓存选项。
  4. UI:使用 CachedChewiePlus 小部件显示视频播放器,并在视频播放器上显示一个浮动操作按钮来控制播放/暂停。

这个示例展示了如何使用 cached_chewie_plus 插件在 Flutter 应用中实现一个简单的视频播放器,并启用了视频缓存功能。你可以根据需要调整缓存配置和其他参数。

回到顶部