My use case is that I have an mp3 file playing in the background that uses audio_service and just_audio packages in flutter. Let's say the file is 'A'.
My app lets 'A' download from url to local file while playing 'A' from url (a separate background task).
Series of steps:
- just_audio plays 'A' from url (for ex. https://something/A.mp3)
- 'A' is downloaded from url to my file (file:///something/A.mp3)
- 'A' is still playing in the background.
- as the 'A' is downloaded, I want to change the audio source of the player from http uri to file uri.
As I am using a queue, I use concatenatingAudioSource to set the source of the player.
I tried to remove old uri and add the new uri and bring back the state before changing the uri. (as below)
bool isPlaying = _player.playing;
Duration position = _player.position;
int index = params['index'];
bool isCurrentItem = _player.currentIndex == index;
await concatenatingAudioSource.removeAt(index);
await concatenatingAudioSource.insert(
index, AudioSource.uri(Uri.parse(params['uri'])));
updateUriInQueue();
// broadcast the queue
await AudioServiceBackground.setQueue(queue);
// Note: a small break might occur when changing the state
// return to it's original state after changing uri
if (!isCurrentItem) return;
await _player.seek(position, index: index);
if (isPlaying) _player.play();
For a side-note, I don't use the mediaItem.id as a URI and have it stored inside mediaItem.extras.
From the above code, it clearly is seen that the player stops and plays after the uri is changed. I would like to know if there is a smoother way to change the player uri without disturbing the output.