YouTubeAudioSource class extends StreamAudioSource from just_audio to provide seamless YouTube audio streaming with adaptive quality selection.
Overview
YouTubeAudioSource enables direct streaming of YouTube audio without downloading entire videos. It:
- Fetches audio-only streams from YouTube using
youtube_explode_dart - Supports quality selection (high/low bitrate)
- Handles throttled streams with chunk-based requests
- Integrates with
just_audioplayer for background playback
lib/resources/services/youtube/youtube_audio_service.dart
Credit: Based on implementation from jhelumcorp/gyawun
Constructor
Creates a YouTube audio source for a specific video.YouTube video ID (e.g., ‘dQw4w9WgXcQ’)
Audio quality: ‘high’ or ‘low’
Optional metadata tag (typically a MediaItem)
Public Methods
request
Fetches an audio stream segment for the specified byte range.Starting byte position (default: 0)
Ending byte position (default: end of stream)
Future<StreamAudioResponse>
The response includes:
sourceLength- Total audio file size in bytescontentLength- Size of requested segmentoffset- Starting position of segmentstream- Audio data streamcontentType- MIME type of audio codec
Quality Selection
High Quality
Selects the audio stream with the highest bitrate from available audio-only streams.Low Quality
Selects the audio stream with the lowest bitrate to minimize bandwidth usage.Throttling Handling
For throttled YouTube streams, the audio source:- Limits chunk size to ~10MB per request
- Prevents buffer overflow in ExoPlayer backend
- Automatically manages byte range requests
Integration with MyAudioHandler
TheYouTubeAudioSource is used in MyAudioHandler.initSongs() to handle YouTube URLs in audiobook files:
YouTube Client Configuration
The service uses theAndroidVR YouTube client for improved compatibility:
Audio Format Selection
The source selects audio streams with these priorities:- Audio-only streams (no video data)
- Sorted by bitrate (ascending or descending based on quality)
- First available stream if no audio-only streams exist
Error Handling
Therequest method throws exceptions for:
- No available audio streams for the video
- Network failures during stream fetch
- Invalid video IDs
Usage in AudioSource List
Combine with other audio sources in a playlist:Performance Considerations
- Streaming overhead: YouTube streams require network connection throughout playback
- Chunk size: Throttled streams use 10MB chunks to balance buffering and memory
- Quality impact: High quality streams use more bandwidth but provide better audio fidelity
- Caching: The underlying
just_audioplayer may cache segments in memory
Limitations
- Requires active internet connection
- No offline playback support
- YouTube stream URLs expire after some time
- Subject to YouTube’s rate limiting and availability