initialize method

Future<void> initialize()

Attempts to open the given dataSource and load metadata about the video.

Implementation

Future<void> initialize() async {
  final bool allowBackgroundPlayback =
      videoPlayerOptions?.allowBackgroundPlayback ?? false;
  if (!allowBackgroundPlayback) {
    _lifeCycleObserver = _VideoAppLifeCycleObserver(this);
  }
  _lifeCycleObserver?.initialize();
  _creatingCompleter = Completer<void>();

  late DataSource dataSourceDescription;
  switch (dataSourceType) {
    case DataSourceType.asset:
      dataSourceDescription = DataSource(
        sourceType: DataSourceType.asset,
        asset: dataSource,
        package: package,
      );
    case DataSourceType.network:
      dataSourceDescription = DataSource(
        sourceType: DataSourceType.network,
        uri: dataSource,
        formatHint: formatHint,
        httpHeaders: httpHeaders,
        drmConfigs: drmConfigs,
        playerOptions: playerOptions,
        streamingProperty: streamingProperty,
      );
    case DataSourceType.file:
      dataSourceDescription = DataSource(
        sourceType: DataSourceType.file,
        uri: dataSource,
      );
    case DataSourceType.contentUri:
      dataSourceDescription = DataSource(
        sourceType: DataSourceType.contentUri,
        uri: dataSource,
      );
  }

  if (videoPlayerOptions?.mixWithOthers != null) {
    await _videoPlayerPlatform
        .setMixWithOthers(videoPlayerOptions!.mixWithOthers);
  }

  _playerId = (await _videoPlayerPlatform.create(dataSourceDescription)) ??
      kUninitializedPlayerId;
  _creatingCompleter!.complete(null);
  final Completer<void> initializingCompleter = Completer<void>();

  void eventListener(VideoEvent event) {
    if (_isDisposed) {
      return;
    }

    switch (event.eventType) {
      case VideoEventType.initialized:
        value = value.copyWith(
          duration: event.duration,
          size: event.size,
          isInitialized: event.duration != null,
          errorDescription: null,
          isCompleted: false,
        );
        assert(
          !initializingCompleter.isCompleted,
          'VideoPlayerController already initialized. This is typically a '
          'sign that an implementation of the VideoPlayerPlatform '
          '(${_videoPlayerPlatform.runtimeType}) has a bug and is sending '
          'more than one initialized event per instance.',
        );
        if (initializingCompleter.isCompleted) {
          throw StateError('VideoPlayerController already initialized');
        }
        initializingCompleter.complete(null);
        _applyLooping();
        // NOTE(jsuya): The plusplayer's SetVolume() work when player is
        // paused or played, so it changes the order of _applyPlayPause()
        // and _applyVolume().
        _applyPlayPause();
        _applyVolume();
        _durationTimer?.cancel();
        _durationTimer = _createDurationTimer();
      case VideoEventType.completed:
        // In this case we need to stop _timer, set isPlaying=false, and
        // position=value.duration. Instead of setting the values directly,
        // we use pause() and seekTo() to ensure the platform stops playing
        // and seeks to the last frame of the video.
        pause().then((void pauseResult) => seekTo(value.duration.end));
        value = value.copyWith(isCompleted: true);
        _durationTimer?.cancel();
      case VideoEventType.bufferingUpdate:
        value = value.copyWith(buffered: event.buffered);
      case VideoEventType.bufferingStart:
        value = value.copyWith(isBuffering: true);
      case VideoEventType.bufferingEnd:
        value = value.copyWith(isBuffering: false);
      case VideoEventType.subtitleUpdate:
        final Caption caption = Caption(
          number: 0,
          start: value.position,
          end: value.position + (event.duration?.end ?? Duration.zero),
          text: event.text ?? '',
        );
        value = value.copyWith(caption: caption);
      case VideoEventType.unknown:
        break;
    }
  }

  if (closedCaptionFile != null) {
    _closedCaptionFile ??= await closedCaptionFile;
    value = value.copyWith(caption: _getCaptionAt(value.position));
  }

  if (drmConfigs?.licenseCallback != null) {
    _channel.setMethodCallHandler((MethodCall call) async {
      if (call.method == 'requestLicense') {
        final Map<dynamic, dynamic> argumentsMap =
            call.arguments as Map<dynamic, dynamic>;
        final Uint8List message = argumentsMap['message']! as Uint8List;
        return drmConfigs!.licenseCallback!(message);
      } else {
        throw Exception('not implemented ${call.method}');
      }
    });
  }

  void errorListener(Object obj) {
    final PlatformException e = obj as PlatformException;
    value = VideoPlayerValue.erroneous(e.message!);
    _timer?.cancel();
    _durationTimer?.cancel();
    if (!initializingCompleter.isCompleted) {
      initializingCompleter.completeError(obj);
    }
  }

  _eventSubscription = _videoPlayerPlatform
      .videoEventsFor(_playerId)
      .listen(eventListener, onError: errorListener);
  return initializingCompleter.future;
}