setAudioSource method

Future<Duration?> setAudioSource(
  1. AudioSource source,
  2. {bool preload = true,
  3. int? initialIndex,
  4. Duration? initialPosition}
)

Sets the source from which this audio player should fetch audio.

By default, this method will immediately start loading audio and return its duration as soon as it is known, or null if that information is unavailable. Set preload to false if you would prefer to delay loading until some later point, either via an explicit call to load or via a call to play which implicitly loads the audio. If preload is false, a null duration will be returned. Note that the preload option will automatically be assumed as true if playing is currently true.

Optionally specify initialPosition and initialIndex to seek to an initial position within a particular item (defaulting to position zero of the first item).

When preload is true, this method may throw:

  • Exception if no audio source has been previously set.
  • PlayerException if the audio source was unable to be loaded.
  • PlayerInterruptedException if another audio source was loaded before this call completed or the player was stopped or disposed of before the call completed.

Implementation

Future<Duration?> setAudioSource(
  AudioSource source, {
  bool preload = true,
  int? initialIndex,
  Duration? initialPosition,
}) async {
  if (_disposed) return null;
  _audioSource = null;
  _initialSeekValues =
      _InitialSeekValues(position: initialPosition, index: initialIndex);
  _playbackEventSubject.add(_playbackEvent = PlaybackEvent(
      currentIndex: initialIndex ?? 0,
      updatePosition: initialPosition ?? Duration.zero));
  _audioSource = source;
  _broadcastSequence();
  Duration? duration;
  if (playing) preload = true;
  if (preload) {
    duration = await load();
  } else {
    await _setPlatformActive(false)?.catchError((dynamic e) async => null);
  }
  return duration;
}