Skip to content

Local Subtitle (File Subtitle)

Muhammad Hasan Alasady edited this page May 24, 2021 · 1 revision

Local Subtitles (File Subtitles)

You have two ways to use subtitle files locally on your device, whether it is (Android, iOS, Linux, Windows, Mac, Web), firstly using SubtitleController and it's the easily way, secondly by using SubtitleProvider and SubtitleParser, this are both of ways:

  • By SubtitleController:

Firstly provide the file of subtitle, after that you can use SubtitleProvider.fromFile(file) or FileSubtitle(file):

var file = File('example/data.vtt');
var controller = SubtitleController(
  provider: SubtitleProvider.fromFile(file),
);

Or

var file = File('example/data.vtt');
var controller = SubtitleController(
  provider: FileSubtitle(file),
);
  • By SubtitleProvider and SubtitleParser:

Like the last one, provide the subtitle file and provider, after that create a new object of SubtitleObject and await it to preparing the subtitle data, in the last you can use SubtitleParser to parsing the subtitles:

var file = File('example/data.vtt');

SubtitleProvider provider = FileSubtitle(file);
SubtitleObject object = await provider.getSubtitle();
SubtitleParser parser = SubtitleParser(object);     

After creating the controller you have to initialize it by call controller.initial(), it's async function, so you have to await it.

await controller.initial();

What is next?

When you intialize it, you can use this methods to dealing with subtitles using SubtitleController, see the SubtitleController Documentation for more. Check the API Reference for more.

Example

import 'package:subtitle/subtitle.dart';
import 'package:universal_io/io.dart';

void main(List<String> args) async {
  //! By using controller - it's easly way
  var file = File('example/subtitles.vtt');
  var controller = SubtitleController(
      provider: SubtitleProvider.fromFile(
    file,
    type: SubtitleType.vtt,
  ));

  await controller.initial();
  printResult(controller.subtitles);
}

void printResult(List<Subtitle> subtitles) {
  subtitles.sort((s1, s2) => s1.compareTo(s2));
  for (var result in subtitles) {
    print(
        '(${result.index}) Start: ${result.start}, end: ${result.end} [${result.data}]');
  }
}