The audio_service package manages streaming audio from a URL. Is there a way to simultaneously write the audio to disk as well?
Note: In python, one can do this by setting stream=True
when calling requests
methods. I'm looking for a way to do this via a flutter package.
The audio_service package manages streaming audio from a URL.
audio_service doesn't manage streaming audio, it manages your media notification. The way it works is: let's say you have already written an app that plays audio using some plugin XYZ, but you want to now just add a media notification so that your app can be controlled from the background. Then you use audio_service to wrap around your "existing" audio code.
So your question is really about what to do for your existing audio code which audio_service wraps around.
If you are following the audio_service official example, it demonstrates using the just_audio plugin to stream audio from a URL, so let's answer in terms of that. You can easily modify the official example by using just_audio's LockCachingAudioSource
.
So for example, whenever in that example you see AudioSource.uri
, just replace that code with LockCachingAudioSource
and it will do what you want. That's it.
But to demonstrate some of the capabilities of LockCachingAudioSource
in a bit more detail, here is a short demo of the way it works:
final source = LockCachingAudioSource(Uri.parse(url));
await player.setAudioSource(source);
await player.play();
The location of the cache file is by default chosen by the plugin, but you can obtain it here:
final cacheFile = await source.cacheFile;
You can clear the cache with:
await source.clearCache();
If you want to choose the location of the cache file, you can do so when constructing the source:
final source = LockCachingAudioSource(
Uri.parse(url),
cacheFile: File('/your/preferred/path.mp3'),
);