loadController method
Asynchronous method to load and initialize the video controller.
Implementation
Future<void> loadController() async {
/// Create an instance of YoutubeExplode
var yt = YoutubeExplode();
/// Get the video manifest for the given video ID.
var manifest = await yt.videos.streamsClient.getManifest(videoId);
/// Get the video URL (use the second stream if available, otherwise use the first).
var videoUrl = manifest.streams.length > 1
? manifest.streams[1].url.toString()
: manifest.streams.first.url.toString();
/// Get the closed captions manifest for the given video ID.
var trackManifest = await yt.videos.closedCaptions.getManifest(videoId);
/// Get the caption track info for the specified language (default to English).
var trackInfo = trackManifest.getByLanguage(captionLanguageCode ?? "en");
/// Variable to store the closed caption track.
ClosedCaptionTrack? tracks;
if (trackInfo.isNotEmpty) {
/// Get the VTT format caption track, if available.
tracks = await yt.videos.closedCaptions.get(trackInfo.firstWhere(
(track) => track.format.formatCode == "vtt",
orElse: () => trackInfo.first));
} else if (trackManifest.tracks.isNotEmpty) {
/// Get the first caption track from the manifest if no specific language track is available.
tracks = await yt.videos.closedCaptions.get(trackManifest.tracks.first);
}
/// Create the video player controller with the video URL.
controller = VideoPlayerController.networkUrl(Uri.parse(videoUrl));
/// Initialize the video player controller.
await controller?.initialize();
/// Set the looping option for the video.
await controller?.setLooping(setLoop);
/// If there are caption tracks, load them as WebVTT.
if (tracks != null) _loadWebVTT(tracks.captions);
}