'Rewinding to an unloaded section stops the audio
There is a track stored in mongo, it needs to be selected in the ReactNative application (so it doesn’t matter, although the link in the browser), in general, this does not cause problems, but as soon as I try to rewind to an unloaded section, stops the audio. With headers, with bytes, everything seems to be ok.
async playTrack(id: string, res: Response, req: RequestWithTokenData) {
const track = await this.findOneById(id);
if (!track) {
throw new CustomHttpException(ErrorTranslateKey.trackNotFound, HttpStatus.NOT_FOUND);
}
let fondedFile: { length: number, chunkSize: number } | undefined;
const { db } = this.connection;
const bucket = new mongo.GridFSBucket(db, {
bucketName: 'tracks',
});
await bucket.find({ _id: new ObjectId(track.trackId) }).forEach((file) => {
fondedFile = file;
});
if (!fondedFile) {
throw new CustomHttpException(ErrorTranslateKey.trackNotFound, HttpStatus.NOT_FOUND);
}
// @ts-ignore
const { range: rangeHeader } = req.headers;
const range = rangeHeader ? rangeHeader.replace(/bytes=/, '').split('-') : [];
range[0] = range[0] ? parseInt(range[0], 10) : 0;
range[1] = range[1] ? parseInt(range[1], 10) : fondedFile.length;
const { start, end } = { start: range[0], end: range[1] };
const downloadStream = bucket.openDownloadStream(track.trackId);
res.set('content-length', String(end - start));
res.set('content-range', `bytes ${start}-${end - 1}/${fondedFile.length}`);
res.set('content-type', 'audio/mp3');
res.set('accept-ranges', 'bytes');
downloadStream.on('data', (chunk) => {
res.write(chunk);
});
downloadStream.on('error', () => {
res.sendStatus(404);
});
downloadStream.on('end', () => {
res.end();
});
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
