I'm attempting to stream an mp3 file as response to a get request from the client. I got as far as receiving a buffer and making it play. However when I made the buffer play with the web audio API, I bumped into a problem; The song (almost?) never finishes, I logged the buffer I'm reading from, and for whatever reason, it appears that it's not the same size everytime (and as it should be), does anyone know why this could be the case?
My server code:
app.get(`/stest`, async (req, res) => {
let f = fs.createReadStream(`./archive/Kill_Of_The_Night.mp3`)
console.log(f)
console.log(typeof(f))
// res.send(f)
// f.pipe(res)
f.on('open', () => {
console.log(`opened`)
res.attachment(`KillOfTheNight.mp3`)
f.pipe(res)
})
f.on('end', () => {
console.log(`ended`)
})
f.on('error', (e) => {
console.log(e)
})
})
My client code:
button.addEventListener('click', async () => {
fetch(`/stest`).then(async (res) => {
const audioContext = new AudioContext()
console.log(res)
let reader = res.body.getReader()
console.log(reader)
console.log(reader.closed)
reader.read().then(({ value, done }) => {
console.log(value.buffer)
console.log(done)
let b = undefined
audioContext.decodeAudioData(value.buffer, (buffer) => {
b = buffer
let source = audioContext.createBufferSource()
source.buffer = b
source.connect(audioContext.destination)
source.start(0)
}).catch((e) => {
console.log(e)
})
}).catch(() => {
console.log(e)
})
}).catch((e) => {
console.log(e)
})
})
Now when I log "value.buffer", I get a different size everytime, as visible in this screenshot.
Does anyone know I can make sure the entire file is within the buffer so that the audio does not cut off in the middle of the track?
Thanks for reading!