Skip to content

Instantly share code, notes, and snippets.

@WillKirkmanM
Created December 18, 2023 15:42
Show Gist options
  • Save WillKirkmanM/7e50ff9891c9660e3a584fecb47ecd21 to your computer and use it in GitHub Desktop.
Save WillKirkmanM/7e50ff9891c9660e3a584fecb47ecd21 to your computer and use it in GitHub Desktop.
Media Streaming in Rust (Partial Content 206)
async fn stream_song() -> impl Responder {
let media = "MEDIA PATH"
let bitrate = 1000;
let start = 0;
let end = seconds * bitrate * 1000 / 8; // convert seconds to bytes
let mut file = File::open(media).unwrap();
file.seek(SeekFrom::Start(start)).unwrap();
let mut buffer = vec![0; end as usize];
file.read_exact(&mut buffer).unwrap();
HttpResponse::PartialContent()
.append_header((header::CONTENT_RANGE, format!("bytes {}-{}/{}", start, end, file.metadata().unwrap().len())))
.append_header((header::ACCEPT_RANGES, "bytes"))
.append_header((header::CONTENT_LENGTH, (end - start + 1).to_string()))
.body(buffer)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment