flutterlive-streamingjust-audio

Flutter [Just audio] - Access the raw byte data from a stream link which is being played


I've a simple use case where there's a need to be able to record a live stream which is being played with the purpose of rewinding it on the request of a user.

There were 2 attempts which I tried:

  1. Get a StreamedResponse from a simple http call and write the data to a temporary mp3 file. It works but the issue with this approach however is that I believe there'll be 2 network calls to the same stream link since somewhere under the hood I assume just audio will have to do the same

  2. Open a sound recorder and try recording the original stream from just audio which is being played. This works as well eliminating the first issue but with this, background noise is recorded as well due to which the quality of the recording is noticeably different from the original.

Is there a way in which we could get the access the byte data from the just audio library itself. It'll allow me to follow the same approach as the first try, without the network call. I tried going through the dart specific implementation of the just audio package but was not able to find any point of access. It's very much possible that I missed it or am not aware of a method to extract it from what's available.


Solution

  • One possibility is to create a custom subclass of StreamAudioSource and then set it as your audio source. This is a way of feeding your own stream of bytes into just_audio and get it to play it. In your implementation, you'll need to open your own HTTP connection to the URL, and as you read the response stream, you'll save a copy of all of those bytes into your own file, but you'll also return those bytes as the return value in your StreamAudioSource so that those same bytes will be fed into the just_audio player. This way, the bytes are only downloaded once.

    The plugin also comes with an example subclass of StreamAudioSource called LockCachingAudioSource which does almost exactly this, except it is only designed and tested for finite duration audio. You could test it on your URL to see if it works, or if it doesn't, you could use that class as inspiration for implementing your own subclass.