简体   繁体   中英

How to convert audiopath to audio file in react-native and send to node.js

I want to send audio wav file from my react-native application to a postnodejs/express route in a multipart/form-data request.

Using the https://github.com/goodatlas/react-native-audio-record package. I got the path to my recorded audio file as

audioFile = await AudioRecord.stop();
console.log(audioFile);

/*
this is what i get
/data/user/0/com.docassistant/files/test.wav
*/

//STUCK HERE AT THIS LOGIC //I need to convert this path to a file and send this as follows

let file = new File([blob], `test.wav`, {
      type: "audio/wav"
});
const formData = new FormData();
formData.append("file", file);

axios
.post(`http://192.168.0.104:8081/postAudio`, formData, {
    headers: {
          "Content-Type": "multipart/form-data"
     }
})
.then(response => {
     console.log(response);
})
.catch(error => {
        console.log(error);
});

Also, I tried sending blob using rn-fetch-blob but got bad request error.

This is my postrequest at nodejs. Works fine with postman .

//Route.js
app.post('/postAudio', (req, res) => {

    const form = new multiparty.Form()
    form.parse(req, (error, fields, files) => {
        if (error) throw new Error(error);
        try {
            const path = files.file[0].path;
            const buffer = Fs.readFileSync(path);
            ....
            ....
            ....

You need to convert filepathAudio to base64.and send base64 to api,on backend side it will encode to audio file

import and install RNFetchBlob

import RNFetchBlob from 'rn-fetch-blob'

const onStopRecord = async () => {
    const result = await audioRecorderPlayer.stopRecorder();
    audioRecorderPlayer.removeRecordBackListener();
    setRecordSecs(0)
    console.log(result);
    RNFetchBlob.fs.readFile(result, 'base64')
        .then((data) => {
            console.log(data, 'fire')
            setVoice(data)
        })
}

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