initialize method

Future<int> initialize()

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

Implementation

Future<int> initialize() async {
  _creatingCompleter = Completer<void>();

  DataSource? dataSourceDescription;
  switch (dataSourceType) {
    case DataSourceType.asset:
      dataSourceDescription = DataSource(
        sourceType: DataSourceType.asset,
        asset: dataSource,
        package: package,
      );
      break;
    case DataSourceType.network:
      dataSourceDescription = DataSource(
        sourceType: DataSourceType.network,
        uri: dataSource,
        formatHint: formatHint,
      );
      break;
    case DataSourceType.file:
      dataSourceDescription = DataSource(
        sourceType: DataSourceType.file,
        uri: dataSource,
      );
      break;
  }
  _textureId =
      await VideoPlayerPlatform.instance.create(dataSourceDescription);
  _creatingCompleter!.complete(null);
  final Completer<int> initializingCompleter = Completer<int>();

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

    switch (event.eventType) {
      case VideoEventType.initialized:
        value = value.copyWith(
          duration: event.duration,
          size: event.size,
        );
        initializingCompleter.complete(_textureId);
        _applyLooping();
        _applyVolume();
        _applyPlayPause();
        if (onCanPlay != null) onCanPlay!();
        break;
      case VideoEventType.completed:
        if (onEnded != null) onEnded!();
        value = value.copyWith(isPlaying: false, position: value.duration);
        _timer?.cancel();
        break;
      case VideoEventType.bufferingUpdate:
        value = value.copyWith(buffered: event.buffered);
        break;
      case VideoEventType.bufferingStart:
        value = value.copyWith(isBuffering: true);
        break;
      case VideoEventType.bufferingEnd:
        if (onCanPlayThrough != null) onCanPlayThrough!();
        value = value.copyWith(isBuffering: false);
        break;
      case VideoEventType.unknown:
        onError!(MEDIA_ERR_ABORTED, 'unknown video error');
        break;
    }
  }

  void errorListener(Object obj) {
    final PlatformException e = obj as PlatformException;
    if (onError != null) onError!(MEDIA_ERR_NETWORK, e.message);
    value = VideoPlayerValue.erroneous(e.message);
    _timer?.cancel();
  }

  _eventSubscription = VideoPlayerPlatform.instance
      .videoEventsFor(_textureId)
      .listen(eventListener, onError: errorListener);
  return initializingCompleter.future;
}