简体   繁体   中英

Playing audio - React / NodeJS / MongoDB- GridFS

i have the following project structure:

  • NodeJS is my back-end: used for upload .mp3 on my mongodb and stream this. I used GridFsBucket for upload/stream
  • React is my front-end and work with Redux store: so, i've two pages, first for upload .mp3 file with FormData and the second is for stream-playing audio.

My upload stage work good, i push the selected .mp3 file on my back-end and with the help of GridFS create my collections on my MongoDB (fs.files and fs.chunks).

I playing my .mp3 from the backend at the http://site:4000/play/myMp3Code , this create a player that reproduce my .mp3. So it's ok.

My problem is on the stream-playing stage on React, because chunks(is it a chunks?) come on Redux but i don't know how to play it from my React web page.

This is my playing handle on backend

const filename = req.params.filename;

        const bucket = new mongoose.mongo.GridFSBucket(mongoose.connection.db, {
            chunkSizeBytes: 1024,
            bucketName: 'fs'
        });

        const downloadStream = bucket.openDownloadStreamByName(filename);

        downloadStream.on('data', (chunk) => {
            res.write(chunk);
        });

        downloadStream.on('error', () => {
            res.sendStatus(404);
        });

        downloadStream.on('end', () => {
            res.end();
        });

And my actions on Redux

export const playTrack = (path, id) => {
    return async dispatch => {
        try {
            const track = await api.call('get',`tracks/${path}/${id}`);

            console.log("Track action: ", track);

        dispatch(currentTrack(track));
            dispatch(removeError());
        } catch (err) {
            const {error} = err.response.data;
            dispatch(addError(error.message));
        }
    };
};

Example of console.log output from Redux action

���T!1AQa"q��2�#BR������3brCS��$���4Tcs�D��%��EUd����5����+!1AQ"2aBq#R3�$��?��v�.A  �UY�d[MVj�?�  1u
��D���MM1�u*곧TXR��X��A ,ְ���+#h�J��*)gQ��i�R:�Ut5�9���Ŋ�)ע%�r�X��c�&ȣ�����GD�B=c^�6T� 2y,�F���\*��
�H���*�Lҋ ....

My question is the following: How can i playing my .mp3 directly from my frontend? Can i play this above data from Reat?

Hope i've explained well. Thanks for answers and for reading

我认为流是可以的,您所要做的就是发送带有正确标题的响应:(内容类型:音频/ mpeg),浏览器应该播放它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM