Creating a streaming (audio) response
See original GitHub issueIt took me a little while to get this right so I wonder if you can see this as an addition to the docs somewhere? In my case I am loading audio as bytes from a database and I create a response in the following way:
from io import BytesIO
from starlette.endpoints import HTTPEndpoint
from starlette.requests import Request
from starlette.responses import StreamingResponse
class AudioEndpoint(HTTPEndpoint):
async def get(self, request: Request) -> StreamingResponse:
"""Return an mp3 audio stream."""
# Load the content from the database.
audio = ...
headers = {
"Content-Length": str(len(audio))
}
return StreamingResponse(
self.stream_audio(record), media_type="audio/mpeg3",
headers=headers
)
@staticmethod
async def stream_audio(record: bytes, chunk_size: int = 4096):
with BytesIO(record) as stream:
data = stream.read(chunk_size)
while data:
yield data
data = stream.read(chunk_size)
Hints for improvements are, of course, welcome 😉
Issue Analytics
- State:
- Created 5 years ago
- Comments:5 (3 by maintainers)
Top Results From Across the Web
A Step By Step Guide To Create An Audio Streaming Platform
Any kind of streaming website will definitely need an audio player. Make it customizable, with options like play, pause, rewind, stop, shuffle, ...
Read more >How to build an audio streaming server in Go - Medium
We first Initialize() portaudio, and defer Terminate() . We will then create a buffer slice, and set it to the same length as...
Read more >Audio and Video Delivery - Developer guides - MDN Web Docs
Whether we are dealing with pre-recorded audio files or live streams, the mechanism for making them available through the browser's <audio> and ...
Read more >How To Transcribe Streams of Audio Data in Real-Time with ...
These experiments are all performed offline and take some time to run in order to generate the output. In fact, once you send...
Read more >Build an Audio Livestream App with Twilio Live
All users start out in audience mode — when they first arrive at the Dashboard, this component will list the ongoing streams that...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I think I was struggling a bit with the decision to send everything as one big chunk or whether to stream it. That’s not really Starlette specific, though, so probably current docs are fine and maybe someone is happy to find this here on GitHub.
Ah sure. No, don’t do that. 😃