Is it possible to append bytes while just_audio is playing from StreamSource?

99 Views Asked by At

I'm using text to synthesize speech, and since the text is very long I can't wait until it's fully synthesized before playing it. I plan to use websocket technology to synthesize and play at the same time. I use just_audio to play the synthesized bytes. When the new clip is synthesized, I need to add it to the bytes currently being played.

So I'm wondering if it's possible to append bytes when just_audio plays from a StreamSource?

1

There are 1 best solutions below

0
On

Yes that is possible.

You should create a custom class that extends StreamAudioSource and receives a ByteStream or Stream<List> in the constructor and assigns it to a class variabele.

Extending StreamAudioSource means you have to provide a request([int? start, int? end]) method that returns a Future< StreamAudioResponse>. This will be called by the audioplayer.

Something like this should work:

class MyCustomSource extends StreamAudioSource {
  final Stream<List<int>> byteStream;
  MyCustomSource(this.byteStream);
  
  @override
  Future<StreamAudioResponse> request([int? start, int? end]) async {
    
    return StreamAudioResponse(
      sourceLength: 0,
      contentLength: 0,
      offset: 0,
      stream: byteStream,
      contentType: 'audio/mpeg',
    );
  }
}

And to use it:

await player.setAudioSource(MyCustomSource(myByteStream));
player.play();

You can keep writing to myByteStream and the player will play it.