Create Flutter audio participant within the background

Create Flutter audio participant within the background

Create Flutter audio participant within the background

1. Introduction

There are a number of packages (e.g. assets_audio_player, audioplayers, just_audio) that may deal with audio play in Flutter, however if you wish to play the audio within the background, you might want to do extra. And I’ll present you the way to do it on this article!

2. Preparation

We want to make use of the audio_service to deal with the background job. audio_service does all of the work to interface with Android, iOS, and different platforms so that you just don’t want to fret about platform-related particulars, and Audio Service isn’t an audio participant; it’s simply an interface to the system audio controls, so you continue to want one other audio play packages for deal with the participant capabilities.

For this text, I’ll use just_audio to deal with the audio service, you can also use different packages to try this. So we have to add the under in pubspec.yaml file:

Do you wish to be a superb buying and selling in cTrader? >> TRY IT! <<

dependencies:
just_audio: ^0.9.36
audio_service: ^0.18.12

The base move needs to be

Flutter UI --> Audio Service --> Audio Handler

so we have to create an audio service and handler!

3. Create the Audio Handler

We can create the audio handler with just_audio first. The handler extends BaseAudioHandler and with QueueHandler

class SimplyAudioPlayerHandler extends BaseAudioHandler with QueueHandler {
// create the simply audio object and supply for play record
closing _player = AudioPlayer();
closing _playlist = ConcatenatingAudioSource(kids: []);
//TODO different logics
//...
}

We have to broadcast all playback state modifications as they occur by way of playbackState inside audio_service, so we are able to use _play.playbackEventStream to map the rework occasions and pipe to playbackState:

Transform a just_audio occasion into an audio_service state, this methodology ought to used from the constructor. Every occasion acquired from the just_audio participant might be remodeled into an audio_service state in order that it may be broadcast to audio_service purchasers.

PlaybackState _transformEvent(PlaybackEvent occasion) {
return PlaybackState(
// setup and permit which management merchandise within the management panel within the telephone's lock display
controls: [
//MediaControl.skipToPrevious,
MediaControl.rewind,
if (_player.playing) MediaControl.pause else MediaControl.play,
MediaControl.stop,
MediaControl.fastForward,
//MediaControl.skipToNext,
],
// setup the motion can be utilized, it'll present the buttons within the telephone's lock display
systemActions: const {
MediaAction.search,
MediaAction.searchForward,
MediaAction.seekBackward,
},
// for android lock display management buttons
androidCompactActionIndices: const [0, 1, 3],
// map the audio service processing state to only audio
processingState: const {
ProcessingState.idle: AudioProcessingState.idle,
ProcessingState.loading: AudioProcessingState.loading,
ProcessingState.buffering: AudioProcessingState.buffering,
ProcessingState.prepared: AudioProcessingState.prepared,
ProcessingState.accomplished: AudioProcessingState.accomplished,
}[_player.processingState]!,
taking part in: _player.taking part in, // is taking part in standing
updatePosition: _player.place, // the present taking part in place
bufferedPosition: _player.bufferedPosition, // the buffered place
pace: _player.pace, // participant pace
queueIndex: occasion.presentIndex, // the index of the present queue
);
}

and We additionally have to load an empty playlist the primary time to load

Future<void> _loadEmptyPlaylist() async {
attempt {
await _player.setAudioSource(_playlist);
} catch (e) {
print(e);
}
}

and put these two init strategies into the constructor

SimplyAudioPlayerHandler() {
_player.playbackEventStream.map(_transformEvent).pipe(playbackState);
_loadEmptyPlaylist();
}

implement the bottom strategies from the audio service

@override
Future<void> play() => _player.play();

@override
Future<void> pause() => _player.pause();

@override
Future<void> search(Duration place) => _player.search(place);

@override
Future<void> cease() async {
await _player.cease();
await playbackState.firstWhere(
(state) => state.processingState == AudioProcessingState.idle);
}

@override
Future<void> addQueueItems(List<MediaItem> mediaItems) async {

closing audioSource = mediaItems.map(_createAudioSource);
_playlist.addAll(audioSource.toList());

closing newQueue = queue.worth..addAll(mediaItems);
queue.add(newQueue);
}

// add the audio merchandise into playlist and queue earlier than taking part in it
@override
Future<void> addQueueItem(MediaItem mediaItem) async {

closing audioSource = _createAudioSource(mediaItem);
_playlist.add(audioSource);

closing newQueue = queue.worth..add(mediaItem);
queue.add(newQueue);
}

@override
Future<void> removeQueueItemAt(int index) async {

_playlist.removeAt(index);

closing newQueue = queue.worth..removeAt(index);
queue.add(newQueue);
}

@override
Future<dynamic> customAction(String title,
[Map<String, dynamic>? extras]) async {
// set the customized motion like adjusting the quantity from the UI
if (title == 'setVolume') {
_player.setVolume(extras!['value']);
}
}

// create the simply audio supply from audio file
// we move the audio file by way of mediaitem.id from UI
UriAudioSource _createAudioSource(MediaItem mediaItem) {
print('add media merchandise=========${mediaItem.id}');
return AudioSource.uri(
Uri.parse(mediaItem.id),
tag: mediaItem,
);
}

the bottom audio handler needs to be completed, however you may as well create some customized strategies primarily based in your necessities, for instance, I wish to get the audio’s complete length, then create the under methodology

Duration? getTotalDuration() => _player.length;

and set the pace under

Future<void> setPlaySpeed(double pace) async {
await _player.setSpeed(pace);
}

resume merchandise

Future<Duration?> resumeMediaItem(
MediaItem merchandise, Duration presentDuration) async {
var index = _getIndex(merchandise);
await _player.search(presentDuration, index: index);
mediaItem.add(merchandise.copyWith(length: _player.length));
await _player.play();
return _player.length;
}

// get the media merchandise index within the playlist for in search of
// in order that we are able to resume it
int _getIndex(MediaItem merchandise) {
int goalIndex = -1;
closing audioSource = _createAudioSource(merchandise);
for (int i = 0; i < _playlist.size; i++) {
closing currentItem = _playlist.kids[i] as UriAudioSource;
// print('present merchandise');
if (currentItem.uri.path == audioSource.uri.path) {
//print('{audioSource.uri.path} index:i');
goalIndex = i;
break;
}
}
// print('get index:$goalIndex');
return goalIndex;
}

test the merchandise whether or not already exists within the playlist, this may keep away from including duplicate merchandise to the record

Future<bool> hasMediaItem(MediaItem merchandise) async {
var index = -1;
if (_playlist.sequence.isNotEmpty) {
index = _getIndex(merchandise);
}
return index >= 0;
}

4. Create the Audio Service

After creating the audio handler, we are able to create the audio service and expose the strategies to UI to name.

I can even use the GetX sample for the instance. So we are able to create a service that extends GetxService

class AudioPlayerService extends GetxService {

// use the audio handler that we created
late SimplyAudioPlayerHandler audioPlayerHandler;
// outline the MediaItem
late MediaItem _currentItem;
// the present audio length
Duration _currentDuration = Duration.zero;
}

initialize the audio handler within the init() occasion

void init() async {
audioPlayerHandler = await AudioService.init(
builder: () => SimplyAudioPlayerHandler(),
config: const AudioServiceConfig(
androidNotificationChannelId: 'com.audioplayer', //set the app bundle id for android
androidNotificationChannelName: 'Flutter Audio Player', //the title to point out within the background participant
androidNotificationOngoing: true,
),
);
}

implement the strategies we outlined within the handler

Future<void> addQueueItem(MediaItem merchandise) async {
_currentItem = merchandise;
await audioPlayerHandler.addQueueItem(merchandise);
}

Future<bool> hasMediaItem(MediaItem merchandise) async {
return await audioPlayerHandler.hasMediaItem(merchandise);
}

Future<void> setPlaySpeed(double pace) async {
await audioPlayerHandler.setPlaySpeed(pace);
}

void setMediaItem(MediaItem merchandise) {
audioPlayerHandler.setMediaItem(merchandise);
}

void setResumeMediaItem(MediaItem? merchandise, Duration presentDuration) {
// print('set resume length:$presentDuration');
if (merchandise != null) {
_currentItem = merchandise;
}
_currentDuration = presentDuration;
}

Future<void> removeAll() async {
audioPlayerHandler.removeAll();
}

Future<Duration?> getTotalDuration() async {
return audioPlayerHandler.getTotalDuration();
}

Future<Duration?> play() =>
audioPlayerHandler.resumeMediaItem(_currentItem, _currentDuration);

Future<void> pause() => audioPlayerHandler.pause();

Future<void> search(Duration place) =>
audioPlayerHandler.resumeMediaItem(_currentItem, place);

Future<void> cease() async {
await audioPlayerHandler.cease();
}

Future<void> setVolume(double quantity) async {
await audioPlayerHandler.customAction('setVolume', {'worth': quantity});
}

The audio service might be easy, simply name the strategies from the handler.

5. Use it within the UI

Create a music mannequin

For exhibiting the music data on lock display, we want the mannequin under:

class SongItem {
closing int id;
String title;
String artist;
String coverImg;
String album;
String audioFilePath;
SongItem(this.id, this.title, this.artist, this.coverImg, this.album, this.audioFilePath);
}

and move the mannequin to the audio participant service

Using the AudioPlayerService

We can simpler to make use of the service by way of GetX, simply put under in important.dart , and you should utilize the service wherever

Get.discover<AudioPlayerService>().init();

and we have to create a MediaItem from the music mannequin

var mediaItem = MediaItem(
id: songItem.audioFilePath, //move the audio file path to MediaItem's id
album: songItem.album,
title: songItem.title,
artist: songItem.artist,
artworkUri: Uri.file(songItem.coverImage),
);

test the music whether or not has been added to the playlist, if not then do it in any other case don’t add the duplicate merchandise

//test and do not add the duplicate merchandise
if (await audioPlayerService.hasMediaItem(mediaItem) &&
resumeDuration.inMilliseconds > 0) {

audioPlayerService.setResumeMediaItem(mediaItem, resumeDuration);
presentDuration.worth = resumeDuration.inMilliseconds.toDouble();
playingItem(resumeDuration);

} else {
audioPlayerService.addQueueItem(mediaItem);
}

take heed to the length for updating

AudioService.place.pay attention((Duration p) {

presentDuration.worth = p.inMilliseconds.toDouble();
currentPosition.worth =
'{p.mmSSFormat} /{completeDuration.worth.mmSSFormat}';
presentDuration.worth = p.inMilliseconds.toDouble();
resumeDuration = p;

//TODO:
// Update the progress bar values primarily based on the present length...
});

and create the bottom management strategies for UI buttons

Future<void> play() async {
audioPlayerService.setResumeMediaItem(null, resumeDuration);
var totalDur = await audioPlayerService.play();
//get the whole length
if (totalDur != null) {
completeDuration.worth = totalDur;
}
// deal with different occasions...
}

Future<void> search(Duration d) async {
isPlaying.worth = true;
await audioPlayerService.search(d);
}

Future<void> pause() async {
isPlaying.worth = false;
await audioPlayerService.pause();
}

I simply roughly clarify the way to use within the UI, there are nonetheless many issues that have to be completed for an entire UI logic, however these are usually not the principle elements of this text 🙂

In the tip, don’t overlook setup the permissions of background audio service in Android and iOS

you could find the under hyperlink from audio_service settings:

Android & iOS

6. Conclusion

I simply demoed the way to play audio within the background with just_audio and audio_service, you can also create the audio handler along with your favourite audio bundle (e.g assets_audio_player, audioplayers …). You can also make extra controls within the rework occasion to make the lock display look good. The customAction is one of the best ways to deal with your customized capabilities.

Ok, please let me know when you’ve got different concepts.

If you loved this text, please observe me right here on Medium for extra tales about .Net Core, Angular, and different Tech! 🙂

HI-FI News

by way of Flutter on Medium https://ift.tt/aTiGozI

May 16, 2024 at 04:30AM