How To create a simple music app in Flutter

To create a simple music app in Flutter, you can follow these steps:

  1. Create a new Flutter project:
flutter create music_app
  1. Add the audio_service and just_audio packages to your pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
audio_service: ^3.3.2
just_audio: ^1.1.1
  1. Import the audio_service and just_audio packages in your main dart file:
import 'package:audio_service/audio_service.dart';
import 'package:just_audio/just_audio.dart';
  1. Create a new MusicPlayer class that extends the AudioServiceBackground class:
class MusicPlayer extends AudioServiceBackground {
// TODO: Add your code here
}
  1. In the MusicPlayer class, define a method to play a song:
Future<void> play(String url) async {
final player = AudioPlayer();
final audio = Audio.network(url);
await player.setUrl(audio);
await player.play();
// TODO: Add code to handle playback updates and completion
}
  1. In the MusicPlayer class, define a method to handle playback updates:
void _updatePlaybackState() {
AudioServiceBackground.setState(
controls: [
MediaControl.pause,
MediaControl.stop
],
processingState: _player.processingState,
playing: _player.playing,
position: _player.position,
);
}
  1. In the MusicPlayer class, define a method to handle playback completion:
void _onComplete() {
_player.stop();
_updatePlaybackState();
onStop();
}
  1. In the MusicPlayer class, override the onStart and onStop methods:
@override
Future<void> onStart(Map<String, dynamic> params) async {
final url = params['url'];
await play(url);
}

@override
Future<void> onStop() async {
await _player.dispose();
}

  1. In the main dart file, call the AudioService.start method to start the music player:
AudioService.start(
backgroundTaskEntrypoint: MusicPlayer().run,
androidNotificationChannelName: 'Music Player',
androidNotificationColor: 0xFF2196f3,
androidNotificationIcon: 'mipmap/ic_launcher',
androidNotificationTitle: 'Music Player',
);

This is just a basic example of how to create a music player app in Flutter using the audio_service and just_audio packages. You can find more information and additional examples in the package documentation and package documentation.