AudioPlayer class

An audio player that plays a gapless playlist of AudioSources.

final player = AudioPlayer();
await player.setUrl('https://foo.com/bar.mp3');
player.play();
await player.pause();
await player.setClip(start: Duration(seconds: 10), end: Duration(seconds: 20));
await player.play();
await player.setUrl('https://foo.com/baz.mp3');
await player.seek(Duration(minutes: 5));
player.play();
await player.pause();
await player.dispose();

You must call stop or dispose to release the resources used by this player, including any temporary files created to cache assets.

Constructors

AudioPlayer.new({String? userAgent, bool handleInterruptions = true, bool androidApplyAudioAttributes = true, bool handleAudioSessionActivation = true, AudioLoadConfiguration? audioLoadConfiguration, AudioPipeline? audioPipeline, bool androidOffloadSchedulingEnabled = false, bool useProxyForRequestHeaders = true, bool useLazyPreparation = true, ShuffleOrder? shuffleOrder, int maxSkipsOnError = 0})
Creates an AudioPlayer.

Properties

allowsExternalPlayback bool
Whether the player allows external playback on iOS/macOS, defaults to false.
no setter
androidAudioSessionId int?
The current Android AudioSession ID or null if not set.
no setter
androidAudioSessionIdStream Stream<int?>
Broadcasts the current Android AudioSession ID or null if not set.
no setter
audioSource AudioSource?
The first AudioSource in the playlist, if any.
no setter
audioSources List<AudioSource>
The playlist.
no setter
automaticallyWaitsToMinimizeStalling bool
Whether the player should automatically delay playback in order to minimize stalling. (iOS 10.0 or later only)
no setter
bufferedPosition Duration
The position up to which buffered audio is available.
no setter
bufferedPositionStream Stream<Duration>
A stream of buffered positions.
no setter
canUseNetworkResourcesForLiveStreamingWhilePaused bool
Whether the player can use the network for live streaming while paused on iOS/macOS.
no setter
currentIndex int?
The index of the current IndexedAudioSource in sequence, or null if sequence is empty.
no setter
currentIndexStream Stream<int?>
A stream broadcasting the current index.
no setter
duration Duration?
The duration of the current audio or null if unknown.
no setter
durationStream Stream<Duration?>
The duration of the current audio.
no setter
effectiveIndices List<int>
Returns shuffleIndices if shuffleModeEnabled is true, otherwise returns the unshuffled indices.
no setter
errorStream Stream<PlayerException>
A stream of errors broadcast by the player.
no setter
hashCode int
The hash code for this object.
no setterinherited
hasNext bool
Whether there is another item after the current index.
no setter
hasPrevious bool
Whether there is another item before the current index.
no setter
icyMetadata IcyMetadata?
The latest ICY metadata received through the audio source, or null if no metadata is available.
no setter
icyMetadataStream Stream<IcyMetadata?>
A stream of ICY metadata received through the audio source.
no setter
loopMode LoopMode
The current loop mode.
no setter
loopModeStream Stream<LoopMode>
A stream of LoopModes.
no setter
nextIndex int?
The index of the next item to be played, or null if there is no next item.
no setter
pitch double
The current pitch factor of the player.
no setter
pitchStream Stream<double>
A stream of current pitch factor values.
no setter
playbackEvent PlaybackEvent
The latest PlaybackEvent.
no setter
playbackEventStream Stream<PlaybackEvent>
A stream of PlaybackEvents.
no setter
playerEvent PlayerEvent
The latest PlayerEvent.
no setter
playerEventStream Stream<PlayerEvent>
A stream of PlayerEvents.
no setter
playerState PlayerState
The current player state containing only the processing and playing states.
no setter
playerStateStream Stream<PlayerState>
A stream of PlayerStates.
no setter
playing bool
Whether the player is playing.
no setter
playingStream Stream<bool>
A stream of changing playing states.
no setter
position Duration
The current position of the player.
no setter
positionDiscontinuityStream Stream<PositionDiscontinuity>
A stream broadcasting every position discontinuity.
no setter
positionStream Stream<Duration>
A stream tracking the current position of this player, suitable for animating a seek bar. To ensure a smooth animation, this stream emits values more frequently on short items where the seek bar moves more quickly, and less frequenly on long items where the seek bar moves more slowly. The interval between each update will be no quicker than once every 16ms and no slower than once every 200ms.
no setter
preferredPeakBitRate double
The preferred peak bit rate (in bits per second) of bandwidth usage on iOS/macOS.
no setter
previousIndex int?
The index of the previous item in play order, or null if there is no previous item.
no setter
processingState ProcessingState
The current ProcessingState.
no setter
processingStateStream Stream<ProcessingState>
A stream of ProcessingStates.
no setter
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
sequence List<IndexedAudioSource>
The current sequence of indexed audio sources.
no setter
sequenceState SequenceState
The current SequenceState.
no setter
sequenceStateStream Stream<SequenceState>
A stream broadcasting the current SequenceState.
no setter
sequenceStream Stream<List<IndexedAudioSource>>
A stream broadcasting the current sequence of indexed audio sources.
no setter
shuffleIndices List<int>
The current shuffled sequence of indexed audio sources.
no setter
shuffleIndicesStream Stream<List<int>>
A stream broadcasting the current shuffled sequence of indexed audio sources.
no setter
shuffleModeEnabled bool
Whether shuffle mode is currently enabled.
no setter
shuffleModeEnabledStream Stream<bool>
A stream of the shuffle mode status.
no setter
skipSilenceEnabled bool
The current skipSilenceEnabled factor of the player.
no setter
skipSilenceEnabledStream Stream<bool>
A stream of current skipSilenceEnabled factor values.
no setter
speed double
The current speed of the player.
no setter
speedStream Stream<double>
A stream of current speed values.
no setter
volume double
The current volume of the player.
no setter
volumeStream Stream<double>
A stream of volume changes.
no setter
webCrossOrigin WebCrossOrigin?
The crossorigin attribute set the <audio> element backing this player instance on web.
no setter
webSinkId String
The current sink ID of the <audio> element backing this instance on web.
no setter

Methods

addAudioSource(AudioSource audioSource) Future<void>
Adds audioSource to the end of the playlist.
addAudioSources(List<AudioSource> audioSources) Future<void>
Adds audioSources to the end of the playlist.
clearAudioSources() Future<void>
Clears the playlist.
createPositionStream({int steps = 800, Duration minPeriod = const Duration(milliseconds: 200), Duration maxPeriod = const Duration(milliseconds: 200)}) Stream<Duration>
Creates a new stream periodically tracking the current position of this player. The stream will aim to emit steps position updates from the beginning to the end of the current audio source, at intervals of duration / steps. This interval will be clipped between minPeriod and maxPeriod. This stream will not emit values while audio playback is paused or stalled.
dispose() Future<void>
Releases all resources associated with this player. You must invoke this after you are done with the player.
insertAudioSource(int index, AudioSource audioSource) Future<void>
Inserts audioSource into the playlist at index.
insertAudioSources(int index, List<AudioSource> audioSources) Future<void>
Inserts audioSources into the playlist at index.
load() Future<Duration?>
Starts loading the playlist and returns the audio duration of the initial AudioSource in the playlist as soon as it is known, or null if unavailable. This method does nothing if the playlist is empty.
moveAudioSource(int currentIndex, int newIndex) Future<void>
Moves the AudioSource in the playlist at currentIndex to newIndex.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
pause() Future<void>
Pauses the currently playing media. This method does nothing if ![playing].
play() Future<void>
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.
removeAudioSourceAt(int index) Future<void>
Removes the AudioSource at index from the playlist.
removeAudioSourceRange(int start, int end) Future<void>
Removes the AudioSources from index start to end from the playlist.
seek(Duration? position, {int? index}) Future<void>
Seeks to a particular position, and optionally to a particular index within sequence.
seekToNext() Future<void>
Seeks to the next item, or does nothing if there is no next item.
seekToPrevious() Future<void>
Seeks to the previous item, or does nothing if there is no previous item.
setAllowsExternalPlayback(bool allowsExternalPlayback) Future<void>
Sets allowsExternalPlayback on iOS/macOS, defaults to false.
setAndroidAudioAttributes(AndroidAudioAttributes audioAttributes) Future<void>
Sets the Android audio attributes for this player. Has no effect on other platforms. This will cause a new Android AudioSession ID to be generated.
setAsset(String assetPath, {String? package, bool preload = true, Duration? initialPosition, dynamic tag}) Future<Duration?>
Convenience method to set the audio source to an asset, preloaded by default, with an initial position of zero by default.
setAudioSource(AudioSource audioSource, {bool preload = true, int? initialIndex, Duration? initialPosition}) Future<Duration?>
Clears the playlist and adds the given audioSource.
setAudioSources(List<AudioSource> audioSources, {bool preload = true, int? initialIndex, Duration? initialPosition, ShuffleOrder? shuffleOrder}) Future<Duration?>
Clears the playlist and adds the given audioSources.
setAutomaticallyWaitsToMinimizeStalling(bool automaticallyWaitsToMinimizeStalling) Future<void>
Sets automaticallyWaitsToMinimizeStalling for AVPlayer in iOS 10.0 or later, defaults to true. Has no effect on Android clients
setCanUseNetworkResourcesForLiveStreamingWhilePaused(bool canUseNetworkResourcesForLiveStreamingWhilePaused) Future<void>
Sets canUseNetworkResourcesForLiveStreamingWhilePaused on iOS/macOS, defaults to false.
setClip({Duration? start, Duration? end, dynamic tag}) Future<Duration?>
Clips the current AudioSource to the given start and end timestamps. If start is null, it will be reset to the start of the original AudioSource. If end is null, it will be reset to the end of the original AudioSource. This method cannot be called from the ProcessingState.idle state.
setFilePath(String filePath, {Duration? initialPosition, bool preload = true, dynamic tag}) Future<Duration?>
Convenience method to set the audio source to a file, preloaded by default, with an initial position of zero by default.
setLoopMode(LoopMode mode) Future<void>
Sets the LoopMode. Looping will be gapless on Android, iOS and macOS. On web, there will be a slight gap at the loop point.
setPitch(double pitch) Future<void>
Sets the factor by which pitch will be shifted.
setPreferredPeakBitRate(double preferredPeakBitRate) Future<void>
Sets preferredPeakBitRate on iOS/macOS, defaults to true.
setShuffleModeEnabled(bool enabled) Future<void>
Sets whether shuffle mode is enabled.
setSkipSilenceEnabled(bool enabled) Future<void>
Sets whether silence should be skipped in audio playback. (Currently Android only).
setSpeed(double speed) Future<void>
Sets the playback speed to use when playing is true, where 1.0 is normal speed. Note that values in excess of 1.0 may result in stalls if the playback speed is faster than the player is able to downloaded the audio.
setUrl(String url, {Map<String, String>? headers, Duration? initialPosition, bool preload = true, dynamic tag}) Future<Duration?>
Convenience method to set the audio source to a URL with optional headers, preloaded by default, with an initial position of zero by default. If headers are set, just_audio will create a cleartext local HTTP proxy on your device to forward HTTP requests with headers included.
setVolume(double volume) Future<void>
Sets the volume of this player, where 1.0 is normal volume.
setWebCrossOrigin(WebCrossOrigin? webCrossOrigin) Future<void>
Sets the crossorigin attribute on the <audio> element backing this player instance on web (see HTMLMediaElement crossorigin ).
setWebSinkId(String webSinkId) Future<void>
Sets a specific device output id on Web.
shuffle() Future<void>
Shuffles the playlist using the ShuffleOrder passed into the constructor, and recursively shuffles each nested AudioSource according to its own ShuffleOrder.
stop() Future<void>
Stops playing audio and releases decoders and other native platform resources needed to play audio. The current audio source state will be retained and playback can be resumed at a later point in time.
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited

Static Methods

clearAssetCache() Future<void>
Clears the plugin's internal asset cache directory. Call this when the app's assets have changed to force assets to be re-fetched from the asset bundle.