Flutter字幕显示插件flutter_captions的使用

Flutter字幕显示插件flutter_captions的使用

安装

要开始使用flutter_captions插件,首先需要在项目的pubspec.yaml文件中添加依赖:

dependencies:
  flutter_captions: ^版本号

然后运行以下命令以获取最新的依赖项:

flutter pub get

示例

您可以从以下示例项目中查看完整的实现:

示例项目

使用

初始化 CaptionWriter

首先,我们需要初始化一个CaptionWriter对象。可以通过默认构造函数或自定义装饰器来完成。

默认构造函数

final writer = CaptionWriter();

自定义装饰器

final writer = CaptionWriter(
  decoration: CaptionWriterDecoration(
    position: CaptionWriterPostion.BottomCenter, // 字幕位置
    fontSize: 12, // 字号
    margins: const EdgeInsets.all(24), // 边距
    shadow: 0.5, // 阴影强度
    outline: 0, // 轮廓宽度
    fontName: 'Arial', // 字体名称
    fontColor: Colors.white, // 字体颜色
    bold: false, // 是否加粗
    italic: false, // 是否斜体
    underlined: false, // 是否下划线
    borderStyle: 0, // 边框样式
    wrapStyle: 0, // 换行样式
    outlineColor: Colors.amber, // 轮廓颜色
  ),
);

添加字幕并生成输出文件

使用CaptionWriter对象的process方法可以将字幕添加到视频中,并返回处理后的文件路径。

String out = await writer.process(File(path), [
  CaptionWriterParams(
    text: 'Hello', // 字幕文本
    time: CaptionWriterTimestamp(start: 65, end: 6500), // 字幕显示时间(毫秒)
  ),
  CaptionWriterParams(
    text: 'Bye',
    time: CaptionWriterTimestamp(start: 6500, end: 16500),
  )
]);

字幕位置

CaptionWriter支持多种字幕位置,具体如下:

  • BottomLeft
  • BottomCenter
  • BottomRight
  • CenterLeft
  • Center
  • CenterRight
  • TopLeft
  • TopCenter
  • TopRight

完整示例代码

以下是一个完整的示例代码,展示了如何使用flutter_captions插件为视频添加字幕。

import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_captions/flutter_captions.dart';
import 'package:images_picker/images_picker.dart';
import 'package:video_player/video_player.dart';

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

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

  [@override](/user/override)
  State<MainApp> createState() => _MainAppState();
}

class _MainAppState extends State<MainApp> {
  VideoPlayerController? controller;
  final writer = CaptionWriter();
  int duration = 0;

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.teal,
          title: Text('Video Caption'),
        ),
        body: Stack(
          fit: StackFit.expand,
          children: [buildContent()],
        ),
      ),
    );
  }

  Widget buildContent() {
    return Column(
      children: [
        TextButton(
          onPressed: () async {
            final v = await ImagesPicker.pick(count: 1, pickType: PickType.video);
            if (v == null) {
              print('error');
              return;
            }
            String path = v.single.path;
            final originalController = VideoPlayerController.file(File(path));
            await originalController.initialize();
            duration = originalController.value.duration.inMilliseconds;
            setState(() {});

            // 添加字幕并生成输出文件
            String out = await writer.process(File(path), [
              CaptionWriterParams(
                text: 'Hello',
                time: CaptionWriterTimestamp(start: 65, end: 6500),
              ),
              CaptionWriterParams(
                text: 'Bye',
                time: CaptionWriterTimestamp(start: 6500, end: 16500),
              )
            ]);

            // 更新视频控制器
            controller = VideoPlayerController.file(File(out));
            await controller?.initialize();
            controller?.play();
            setState(() {});
          },
          child: Container(
            padding: EdgeInsets.all(16),
            color: Colors.green,
            child: Text(
              'Add caption',
              style: TextStyle(color: Colors.white),
            ),
          ),
        ),
        Expanded(
          child: Stack(
            children: [
              // 显示视频
              if (controller != null && (controller?.value.isInitialized ?? false))
                Center(
                  child: Container(
                    padding: EdgeInsets.all(32),
                    child: AspectRatio(
                      aspectRatio: controller!.value.size.aspectRatio,
                      child: Stack(
                        children: [VideoPlayer(controller!)],
                      ),
                    ),
                  ),
                ),
              // 显示进度条
              StreamBuilder<int>(
                stream: writer.timeStream,
                builder: (context, snapshot) {
                  if ((snapshot.data ?? 0) == 0) {
                    return SizedBox();
                  }
                  if (duration == 0) {
                    return Center(
                      child: Text('$duration%'),
                    );
                  }
                  final progress = ((snapshot.data ?? 0) * 100) ~/ duration;
                  return Center(
                    child: Text('$progress%'),
                  );
                },
              )
            ],
          ),
        )
      ],
    );
  }
}

更多关于Flutter字幕显示插件flutter_captions的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter字幕显示插件flutter_captions的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


flutter_captions 是一个用于在 Flutter 应用中显示字幕的插件。它可以帮助你在视频播放时同步显示字幕,支持多种字幕格式(如 .srt, .vtt 等)。以下是如何使用 flutter_captions 插件的基本步骤:

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 flutter_captions 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_captions: ^0.1.0  # 请检查最新版本

然后运行 flutter pub get 来获取依赖。

2. 导入插件

在你的 Dart 文件中导入 flutter_captions 插件:

import 'package:flutter_captions/flutter_captions.dart';

3. 使用 Captions 组件

flutter_captions 提供了一个 Captions 组件,你可以将它放在视频播放器的上方或下方来显示字幕。

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

class _VideoPlayerWithCaptionsState extends State<VideoPlayerWithCaptions> {
  final CaptionsController _captionsController = CaptionsController();

  [@override](/user/override)
  void initState() {
    super.initState();
    _loadCaptions();
  }

  Future<void> _loadCaptions() async {
    final captions = await Captions.loadFromAsset('assets/captions.srt');
    _captionsController.captions = captions;
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Video with Captions'),
      ),
      body: Column(
        children: [
          // 你的视频播放器组件
          VideoPlayerWidget(),

          // 字幕显示组件
          Captions(
            controller: _captionsController,
            style: TextStyle(
              color: Colors.white,
              fontSize: 16.0,
              backgroundColor: Colors.black.withOpacity(0.5),
            ),
          ),
        ],
      ),
    );
  }
}

4. 控制字幕显示

你可以通过 CaptionsController 来控制字幕的显示。例如,你可以根据视频的播放进度来更新字幕:

void _onVideoPositionChanged(Duration position) {
  _captionsController.seek(position);
}

5. 加载字幕文件

你可以从不同的来源加载字幕文件,例如从本地文件、网络或资源文件:

// 从资源文件加载
final captions = await Captions.loadFromAsset('assets/captions.srt');

// 从网络加载
final captions = await Captions.loadFromUrl('https://example.com/captions.vtt');

// 从本地文件加载
final captions = await Captions.loadFromFile(File('path/to/captions.srt'));

6. 自定义字幕样式

你可以通过 style 参数来自定义字幕的样式,例如字体大小、颜色、背景等:

Captions(
  controller: _captionsController,
  style: TextStyle(
    color: Colors.white,
    fontSize: 16.0,
    backgroundColor: Colors.black.withOpacity(0.5),
  ),
),

7. 处理字幕事件

你可以监听字幕事件,例如当字幕开始或结束时执行某些操作:

_captionsController.addListener(() {
  if (_captionsController.isCaptionActive) {
    print('Caption is active: ${_captionsController.activeCaption?.text}');
  } else {
    print('No active caption');
  }
});

8. 销毁控制器

在页面销毁时,记得销毁 CaptionsController 以释放资源:

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