0

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

act-studio
  • 51
  • 1
  • 2
  • 10

1 Answers1

0

I think the stream is OK, all you need to do is send the response with correct headers: (Content-Type: audio/mpeg) and the browser should play it.

Samson Maosa
  • 472
  • 5
  • 11