Невозможно преобразовать файл в двоичный формат для отправки в wit.ai api с помощью node.js - PullRequest
0 голосов
/ 03 июля 2019

Возникла проблема при преобразовании аудиофайла в двоичный формат. Мне нужно отправить его в Wit.AI API, который ожидает данные в этом формате. Я использую node.js. В моем интерфейсе я записываю голос пользователя с помощью модуля Mic-рекордера. Любые предложения приветствуются.

Мой код переднего конца:

var recorder;
function startRecording() {
    recorder = new MicRecorder({
        bitRate: 128
    });
    recorder.start()
}

function stopRecording() {
    recorder.stop().getMp3().then(([buffer, blob]) => {
        console.log(buffer, blob);
        const file = new File(buffer, 'music.mp3', {
            type: blob.type,
            lastModified: Date.now()
        })
        console.log(file)
        axios({
            method: 'post',
            url: `${appUrl}/open_api/voice/send?data=${buffer}`
        }).then(function (res) {
            console.log(res)
            if (res.data.success) {
                console.log('done',res)
            } else {
                console.log(res.data)
            }
        })
    })
};

После успешной записи я хочу отправить файл в мой API для вызова wit.ai / speech api.

Мой код конца:

router.post('/voice/send',                                //chatbot response api
    async (req, res, next) => {
        let thread_id = '99-99-99-99'
        let audioBinary = req.query.data
        console.log(audioBinary)
        let appId = "5d07621d6b79be66a73f4005"
        let sessionId ="10-10-10-10"
        let accessToken = await db.model('ChatBotApp').findOne({
            _id: req.query.key
        }, {
            access_token: 1
        }).lean() 
        var options = {

            method: 'POST',
            uri: 'https://api.wit.ai/speech?v=20190513',
            body : audioBinary,
            encoding: null,
            headers: {
                'Authorization': 'Bearer ' + "HY3ZWSUGPBPD5LWZLRSZ3QJCDC27M6EW",
                'Content-Type': 'audio/mpeg',
            },
            // json: true // Automatically stringifies the body to JSON
        };
        rp(options)
        .then(async function (parsedBody) {
            console.log('this called',parsedBody)
            return
            // let response = await firstEntityValue(parsedBody, appId, message, thread_id)
            // events.emit('Chats', appId, thread_id, message, sessionId, response);
            return res.apiOk(response)
        })
        .catch(function (err) {
            console.log(err)
            return res.apiError('Issue while creating app!', err);
        })


    }
)

1 Ответ

0 голосов
/ 04 июля 2019
 var recorder

   function startRecording() {
     recorder = new MicRecorder({
       bitRate: 128
     });
     recorder.start()
   }

   function stopRecording() {
     recorder.stop().getMp3().then(([buffer, blob]) => {
       console.log(buffer, blob);

       const file = new File(buffer, 'music.mp3', {
         type: blob.type,
         lastModified: Date.now()
       })
       var bodyFormData = new FormData();
       bodyFormData.append('file', file);
       console.log(file)

       axios({
         method: 'post',
         url: `${appUrl}/open_api/voice/send`,
         headers: {
           'Content-Type': 'multipart/form-data'
         },
         data: bodyFormData
       }).then(function (res) {
         console.log(res)
         if (res.data.success) {
           console.log('done', res)
         } else {
           console.log(res.data)
         }
       })
     })
   };


API 
router.post('/voice/send',upload.single('file'), //chatbot response api
        async (req, res, next) => {

            console.log(req.file)
            let thread_id = '99-99-99-99'
            let audioBinary = req.file.buffer
            let appId = "5d07621d6b79be66a73f4005"
            let sessionId = "10-10-10-10"
            let accessToken = await db.model('ChatBotApp').findOne({
                _id: req.query.key
            }, {
                access_token: 1
            }).lean()
            var options = {

                method: 'POST',
                uri: 'https://api.wit.ai/speech?v=20190513',
                headers: {
                    'Authorization': 'Bearer ' + "HY3ZWSUGPBPD5LWZLRSZ3QJCDC27M6EW",
                    'Content-Type': 'audio/mpeg',
                },
                body: audioBinary

                // json: true // Automatically stringifies the body to JSON
            };
            rp(options)
                .then(async function (parsedBody) {
                    console.log('this called', parsedBody)
                    return
                    // let response = await firstEntityValue(parsedBody, appId, message, thread_id)
                    // events.emit('Chats', appId, thread_id, message, sessionId, response);
                    return res.apiOk(response)
                })
                .catch(function (err) {
                    console.log(err)
                    return res.apiError('Issue while creating app!', err);
                })
        })
...