play method

Future<void> play()

Tells the player to play audio at the current speed and volume as soon as an audio source is loaded and ready to play. If an audio source has been set but not preloaded, this method will also initiate the loading. The Future returned by this method completes when the playback completes or is paused or stopped. If the player is already playing, this method completes immediately.

This method causes playing to become true, and it will remain true until pause or stop is called. This means that if playback completes, and then you seek to an earlier position in the audio, playback will continue playing from that position. If you instead wish to pause or stop playback on completion, you can call either method as soon as processingState becomes ProcessingState.completed by listening to processingStateStream.

This method activates the audio session before playback, and will do nothing if activation of the audio session fails for any reason.

Implementation

Future<void> play() async {
  if (_disposed) return;
  if (playing) return;
  _playInterrupted = false;
  // Broadcast to clients immediately, but revert to false if we fail to
  // activate the audio session. This allows setAudioSource to be aware of a
  // prior play request.
  _playbackEvent = _playbackEvent.copyWith(
    updatePosition: position,
    updateTime: DateTime.now(),
  );
  _playingSubject.add(true);
  _playbackEventSubject.add(_playbackEvent);
  final playCompleter = Completer<dynamic>();
  final audioSession = await AudioSession.instance;
  if (!_handleAudioSessionActivation || await audioSession.setActive(true)) {
    if (!playing) return;
    // TODO: rewrite this to more cleanly handle simultaneous load/play
    // requests which each may result in platform play requests.
    final requireActive = _audioSource != null;
    if (requireActive) {
      if (_active) {
        // If the native platform is already active, send it a play request.
        // NOTE: If a load() request happens simultaneously, this may result
        // in two play requests being sent. The platform implementation should
        // ignore the second play request since it is already playing.
        _sendPlayRequest(await _platform, playCompleter);
      } else {
        // If the native platform wasn't already active, activating it will
        // implicitly restore the playing state and send a play request.
        _setPlatformActive(true, playCompleter: playCompleter)
            ?.catchError((dynamic e) async => null);
      }
    }
  } else {
    // Revert if we fail to activate the audio session.
    _playingSubject.add(false);
  }
  await playCompleter.future;
}