setSubtitleTrack method

  1. @override
Future<void> setSubtitleTrack(
  1. SubtitleTrack track, {
  2. bool synchronized = true,
})
override

Sets the current SubtitleTrack for subtitle output.

  • Currently selected SubtitleTrack can be accessed using state.track.subtitle or stream.track.subtitle.
  • The list of currently available SubtitleTracks can be obtained accessed using state.tracks.subtitle or stream.tracks.subtitle.
  • External subtitle track can be loaded using SubtitleTrack.uri or SubtitleTrack.data constructor.
player.setSubtitleTrack(
  SubtitleTrack.uri(
    'https://www.iandevlin.com/html5test/webvtt/upc-video-subtitles-en.vtt',
    title: 'English',
    language: 'en',
  ),
);

Implementation

@override
Future<void> setSubtitleTrack(SubtitleTrack track,
    {bool synchronized = true}) {
  Future<void> function() async {
    if (disposed) {
      throw AssertionError('[Player] has been disposed');
    }
    await waitForPlayerInitialization;
    await waitForVideoControllerInitializationIfAttached;

    if (track.uri || track.data) {
      final String uri;
      if (track.uri) {
        uri = track.id;
      } else if (track.data) {
        // Save the subtitle data to a temporary [File].
        final temp = await TempFile.create();
        await temp.write_(track.id);
        // Delete the temporary [File] upon [dispose].
        release.add(temp.delete_);
        uri = temp.uri.toString();
      } else {
        return;
      }

      await _command(
        [
          'sub-add',
          uri,
          'select',
          track.title ?? 'external',
          track.language ?? 'auto',
        ],
      );
      state = state.copyWith(
        track: state.track.copyWith(
          subtitle: track,
        ),
      );
      if (!trackController.isClosed) {
        trackController.add(state.track);
      }
    } else {
      final name = 'sid'.toNativeUtf8();
      final value = track.id.toNativeUtf8();
      mpv.mpv_set_property_string(
        ctx,
        name.cast(),
        value.cast(),
      );
      calloc.free(name);
      calloc.free(value);
      state = state.copyWith(
        track: state.track.copyWith(
          subtitle: track,
        ),
      );
      if (!trackController.isClosed) {
        trackController.add(state.track);
      }
    }
  }

  if (synchronized) {
    return lock.synchronized(function);
  } else {
    return function();
  }
}