KD YouTube Background Audio

Pub Version License: MIT Platform

A robust, production-ready Flutter package that acts as an elegant wrapper, seamlessly bridging just_audio and youtube_explode_dart. It eliminates boilerplate code by automating the communication between YouTube stream metadata and Flutter's background audio services.

🚀 Key Features

  • 🎧 Seamless Integration: Fully coordinates audio_service with stream data for native lock-screen controls and notification center integration.
  • 🛠️ Stream Optimization: Conveniently handles muxed stream configurations to ensure consistent audio playback stability.
  • 🌐 Universal Web Support: Includes built-in CORS proxy configuration for enhanced reliability on Flutter Web.
  • 🔄 Resilient Playback: Intelligent management of stream state transitions with automatic recovery and position preservation.
  • 📱 Resource Efficiency: Optimized for a low memory footprint during background execution.

🏗️ Architecture / How It Works

This package implements a clean separation of concerns to provide a stable background audio experience:

  1. Resolution: youtube_explode_dart is utilized purely as a data layer to resolve media URLs and metadata from standard Video IDs.
  2. Playback Engine: just_audio handles the actual media decoding and audio rendering.
  3. OS Integration: audio_service manages the native OS background execution, lock-screen controls, and notification center UI.
  4. The Bridge (This Package): Synchronizes state between the data layer and the playback engine, ensuring metadata is correctly displayed on the lock screen and playback persists when the app moves to the background.

⚠️ Technical Considerations

  • Rate Limiting: Since the underlying data resolution relies on public network requests, executing a very high volume of requests from a single IP address in a short time may result in temporary rate-limiting (HTTP 403) by the provider.
  • Flutter Web: Browsers enforce strict cross-origin policies. To use this package on Flutter Web, you must provide a CORS proxy URL during initialization.

📦 Installation

Add the dependency to your pubspec.yaml:

flutter pub add kd_youtube_background_audio

🛠️ Platform Setup

Android

Add the following to your AndroidManifest.xml within the <application> tag:

<service android:name="com.ryanheise.audioservice.AudioService"
    android:foregroundServiceType="mediaPlayback"
    android:export="true"
    tools:ignore="Instantiatable">
    <intent-filter>
        <action android:name="android.intent.action.MEDIA_BUTTON" />
    </intent-filter>
</service>

<receiver android:name="com.ryanheise.audioservice.MediaButtonReceiver"
    android:export="true"
    tools:ignore="Instantiatable">
    <intent-filter>
        <action android:name="android.intent.action.MEDIA_BUTTON" />
    </intent-filter>
</receiver>

iOS

Add the audio background mode to your Info.plist:

<key>UIBackgroundModes</key>
<array>
  <string>audio</string>
</array>

💻 Usage

1. Initialize the Audio Handler

Initialize the service in your main.dart before calling runApp:

import 'package:kd_youtube_background_audio/kd_youtube_background_audio.dart';

void main() async {
  final audioHandler = await AudioService.init<KdYoutubeAudioHandler>(
    builder: () => KdYoutubeAudioHandler(
      // Optional: Set a CORS proxy for Web stability
      corsProxyUrl: kIsWeb ? 'https://your-cors-proxy.com/' : null,
    ),
    config: const AudioServiceConfig(
      androidNotificationChannelId: 'com.your.app.audio',
      androidNotificationChannelName: 'Music Playback',
      androidNotificationOngoing: true,
    ),
  );
  
  runApp(MyApp(audioHandler: audioHandler));
}

2. Play Audio

Stream audio by simply providing a YouTube Video ID. Title and artist are optional and will be automatically resolved via youtube_explode_dart if not provided!

// Basic usage (Auto-resolves title, artist, and thumbnail)
await audioHandler.playFromYoutube(videoId: 'dQw4w9WgXcQ');

// Custom metadata and Advanced Options
await audioHandler.playFromYoutube(
  videoId: 'dQw4w9WgXcQ',
  title: 'Custom Title',
  artist: 'Custom Artist',
  useMuxed: true, 
  cookies: 'your_youtube_session_cookies_here', // Optional: Play age-restricted or private videos
);

3. Fetch Metadata

You can also retrieve video metadata independently using the underlying library's capabilities:

final metadata = await KdYoutubeExtractor.getMetadata('dQw4w9WgXcQ');

print('Title: ${metadata.title}');
print('Author: ${metadata.author}');
print('Duration: ${metadata.duration}');
print('Thumbnail: ${metadata.thumbnailUrl}');

⚖️ Disclaimer

This package is an independent, unofficial wrapper that simply bridges the gap between the just_audio and youtube_explode_dart libraries. It does not host, scrape, or distribute any content on its own.

  • This package is not affiliated with, endorsed by, or sponsored by YouTube or Google LLC.
  • Any reliance on this package is at your own risk. Developers using this package are solely responsible for ensuring their applications comply with YouTube's Terms of Service and any applicable laws.
  • All trademarks, logos, and brand names are the property of their respective owners.

🤝 Contributing

Contributions are welcome! If you encounter any issues or have feature suggestions, please open an issue or submit a pull request on the GitHub repository.

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

👨‍💻 Maintainer

Developed with ❤️ by KhvichaDev.