audio_player_manager 1.0.1 copy "audio_player_manager: ^1.0.1" to clipboard
audio_player_manager: ^1.0.1 copied to clipboard

A comprehensive Flutter audio player manager package that provides a simple and easy to use API for playing audio files with support for just_audio and audioplayers packages.

Flutter Audio Player Manager #

A comprehensive Flutter audio player manager package that provides a unified interface for multiple audio player implementations with advanced features like playlist management and extensible caching.

✨ Features #

  • 🎡 Multiple Audio Engine Support: Choose between audioplayers and just_audio backends
  • πŸ“± Platform Support: Works on Android, iOS, Web, Windows, macOS, and Linux
  • πŸ’Ύ Smart Caching: Integrated with flutter_app_cache_manager for advanced audio caching
  • πŸ“‹ Playlist Management: Create, modify, and manage playlists
  • πŸ”€ Advanced Controls: Shuffle, repeat modes, and gapless playback
  • πŸ“Š Metadata Support: Extract and display audio metadata and artwork
  • πŸŽ›οΈ Audio Effects: Volume control and playback speed adjustment
  • πŸ”§ Highly Configurable: Extensive configuration options for all features
  • πŸ§ͺ Well Tested: Comprehensive test coverage
  • πŸ“š Clean Architecture: Follows SOLID principles with dependency injection

πŸ“¦ Installation #

Add this package to your pubspec.yaml:

dependencies:
  audio_player_manager: ^x.y.z
  audioplayers: ^x.y.z  # Required for AudioPlayers backend
  flutter_app_cache_manager: ^x.y.z  # Optional for advanced caching

πŸš€ Quick Start #

Basic Audio Playback #

import 'package:audio_player_manager/audio_player_manager.dart';

// Create an audio player with default services
final audioPlayer = await AudioPlayerFactory.createWithDefaultServices(
  config: AudioPlayerConfig.defaultConfig(),
);

// Create an audio track
final track = AudioTrack(
  id: 'track_1',
  title: 'My Song',
  artist: 'Artist Name',
  url: 'https://example.com/audio.mp3',
  sourceType: AudioSourceType.network,
);

// Load and play
await audioPlayer.loadTrack(track);
await audioPlayer.play();

// Listen to playback state
audioPlayer.playbackStateStream.listen((state) {
  print('State: ${state.state}');
  print('Position: ${state.position}');
  print('Duration: ${state.duration}');
});

Advanced Caching with flutter_app_cache_manager #

import 'package:audio_player_manager/audio_player_manager.dart';
import 'package:flutter_app_cache_manager/flutter_app_cache_manager.dart';

// Create a cache manager with custom configuration
final CacheConfigurationModel audioConfig = CacheConfigurationModel.audioConfig();
final BaseCacheManagerInterface cacheManager =
    await FlutterCacheManagerImpl.create(audioConfig);

// Create audio player with cache manager
final audioPlayer = await AudioPlayerFactory.createWithDefaultServices(
  config: AudioPlayerConfig(
    enableCaching: true,
    maxCacheSize: 500 * 1024 * 1024, // 500 MB
  ),
  cacheManager: cacheManager,
);

// The audio player will now automatically cache network audio files
final track = AudioTrack(
  id: 'track_1',
  title: 'My Song',
  artist: 'Artist Name',
  url: 'https://example.com/audio.mp3',
  sourceType: AudioSourceType.network,
);

// This will cache the audio automatically if enableCaching is true
await audioPlayer.loadTrack(track);
await audioPlayer.play();

// Manually cache a track for offline playback
await audioPlayer.cacheTrack(track);

// Check cache status
final cacheState = audioPlayer.currentCacheState;
print('Cache state: $cacheState');

// Clear all cached audio
await audioPlayer.clearCache();

Playlist Management #

// Create a playlist
final playlist = Playlist(
  id: 'my_playlist',
  name: 'My Favorite Songs',
  description: 'A collection of my favorite tracks',
  tracks: [
    AudioTrack(
      id: 'track_1',
      title: 'Song 1',
      artist: 'Artist 1',
      url: 'https://example.com/song1.mp3',
      sourceType: AudioSourceType.network,
    ),
    AudioTrack(
      id: 'track_2',
      title: 'Song 2',
      artist: 'Artist 2',
      url: 'https://example.com/song2.mp3',
      sourceType: AudioSourceType.network,
    ),
  ],
  createdAt: DateTime.now(),
  updatedAt: DateTime.now(),
);

// Load and play playlist
await audioPlayer.loadPlaylist(playlist);
await audioPlayer.play();

// Navigate through playlist
await audioPlayer.skipToNext();
await audioPlayer.skipToPrevious();
await audioPlayer.skipToIndex(2);

Custom Services Setup #

// Create services manually for more control
final CacheConfigurationModel audioConfig = CacheConfigurationModel.audioConfig();
final BaseCacheManagerInterface cacheManager =
    await FlutterCacheManagerImpl.create(audioConfig);
final playlistService = await DefaultPlaylistService.create();

final audioPlayer = await AudioPlayerFactory.createPlayer(
  type: AudioPlayerType.audioPlayers,
  config: AudioPlayerConfig.defaultConfig(),
  playlistService: playlistService,
  cacheManager: cacheManager,
);

Advanced Playback Features #

// Set playback speed
await audioPlayer.setSpeed(1.5); // 1.5x speed

// Set volume
await audioPlayer.setVolume(0.8);

// Set repeat mode
await audioPlayer.setRepeatMode(RepeatMode.all);

// Enable shuffle
await audioPlayer.setShuffleMode(ShuffleMode.songs);

// Seek to position
await audioPlayer.seek(Duration(minutes: 2, seconds: 30));

Cache Event Monitoring #

// Listen to cache state changes
audioPlayer.cacheStateStream.listen((cacheState) {
  switch (cacheState) {
    case AudioCacheState.notCached:
      print('Audio not cached');
      break;
    case AudioCacheState.caching:
      print('Caching audio...');
      break;
    case AudioCacheState.cached:
      print('Audio cached successfully');
      break;
    case AudioCacheState.failed:
      print('Caching failed');
      break;
  }
});

πŸ—οΈ Architecture #

This package follows Clean Architecture principles:

lib/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ core/                 # Core interfaces and enums
β”‚   β”œβ”€β”€ models/               # Data models
β”‚   β”œβ”€β”€ implementations/      # Player implementations
β”‚   β”œβ”€β”€ services/            # Service interfaces and implementations
β”‚   └── utils/               # Utilities and factories

πŸ”§ Configuration #

final config = AudioPlayerConfig(
  enableBackgroundPlayback: true,
  enableGaplessPlayback: true,
  enableCaching: true,
  crossfadeDuration: Duration(seconds: 2),
  bufferDuration: Duration(seconds: 20),
  maxCacheSize: 1024 * 1024 * 1024, // 1 GB
  enableAudioEffects: false,
);

🀝 Extending the Package #

Custom Cache Implementation #

The package integrates seamlessly with flutter_app_cache_manager which provides advanced caching features:

// flutter_app_cache_manager is already integrated
// Just pass it to the audio player factory
final CacheConfigurationModel audioConfig = CacheConfigurationModel.audioConfig();
final BaseCacheManagerInterface cacheManager =
    await FlutterCacheManagerImpl.create(audioConfig);
final audioPlayer = await AudioPlayerFactory.createWithDefaultServices(
  config: config,
  cacheManager: cacheManager,
);

Custom Metadata Service #

class MyMetadataService implements MetadataService {
  @override
  Future<AudioMetadata?> extractMetadata(String url) async {
    // Use metadata_god, flutter_audio_metadata, or custom logic
    // Return AudioMetadata object
  }

  // ... implement other methods
}

πŸ“š API Reference #

Core Classes #

  • AudioPlayerInterface: Main interface for audio playback
  • AudioPlayerFactory: Factory for creating player instances
  • AudioTrack: Represents an audio track
  • Playlist: Represents a collection of tracks
  • PlaybackState: Current state of the player

Services #

  • PlaylistService: Interface for playlist management
  • Caching is handled by flutter_app_cache_manager integration

Models #

  • AudioPlayerConfig: Player configuration
  • PlaybackState: Current playback state

Cache Integration #

  • BaseCacheManagerInterface: From flutter_app_cache_manager package
  • AudioCacheState: Enum for cache states (notCached, caching, cached, failed)

πŸ§ͺ Testing #

// Mock services for testing
final mockCacheManager = MockAudioCacheManager();
final mockPlaylistService = MockPlaylistService();

final player = await AudioPlayerFactory.createPlayer(
  type: AudioPlayerType.audioPlayers,
  config: AudioPlayerConfig.defaultConfig(),
  playlistService: mockPlaylistService,
  cacheManager: mockCacheManager,
);

πŸ› Troubleshooting #

Common Issues #

  1. Audio doesn't play: Check that the URL is accessible and the audio format is supported
  2. Background playback not working: Ensure proper platform setup for background audio
  3. Caching not working: Verify storage permissions and available space, ensure enableCaching is true

Platform Setup #

Android

Add to android/app/src/main/AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

iOS

Add to ios/Runner/Info.plist:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

🀝 Contributing #

Contributions are welcome! Please read our Contributing Guide for details.

πŸ“„ License #

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

πŸ™ Acknowledgments #

πŸ“ž Support #

0
likes
160
points
46
downloads

Publisher

unverified uploader

Weekly Downloads

A comprehensive Flutter audio player manager package that provides a simple and easy to use API for playing audio files with support for just_audio and audioplayers packages.

Repository (GitHub)
View/report issues

Topics

#audio #audio-player #just-audio #audio-player-manager #audioplayers

Documentation

API reference

License

MIT (license)

Dependencies

audioplayers, flutter, flutter_app_cache_manager, flutter_shared_utilities, just_audio

More

Packages that depend on audio_player_manager