【发布时间】:2021-06-06 09:54:39
【问题描述】:
从最高级别开始,我正在尝试将 Blob 传递给将转录数据并返回转录本的函数。我正在努力使流程的异步部分正确排列。任何见解将不胜感激。
我正在使用的两个文件如下。在 record.jsx 文件中,我正在调用 googleTranscribe 函数(位于第二个文件中)来完成转录工作并希望返回转录本。这就是我遇到问题的地方 - 我可以获得成绩单但不能将其作为值返回。我知道我在使用 async/await/promises 时做错了,我只是无法弄清楚我做错了什么。
record.jsx
import React from "react";
import googleTranscribe from '../../functions/googletranscribe.js';
const audioType = 'audio/wav';
class Record extends React.Component {
constructor(props) {
super(props);
this.state = {
recording: false,
audioUrl: '',
audios: [],
};
}
componentDidMount() {
const player = document.getElementById('player');
const stopButton = document.getElementById('stop');
const startButton = document.getElementById('start');
const initalizeRecorder = function(stream) {
if (window.URL) {
player.srcObject = stream;
} else {
player.src = stream;
}
const options = {mimeType: 'audio/webm'};
let recordedChunks = [];
const mediaRecorder = new MediaRecorder(stream, options);
mediaRecorder.addEventListener('dataavailable', function(e) {
if (e.data.size > 0) {
recordedChunks.push(e.data);
}
});
mediaRecorder.addEventListener('stop', function() {
const audioData = recordedChunks;
// convert saved chunks to blob
const blob = new Blob(audioData, {type: audioType});
// generate video url from blob
const audioUrl = window.URL.createObjectURL(blob);
googleTranscribe(blob)
.then((response) => {
console.log('transcript: ' + response);
}).catch((error) => {
console.log('error: ' + error);
});
});
startButton.addEventListener('click', function() {
mediaRecorder.start(1000);
});
stopButton.addEventListener('click', function() {
mediaRecorder.stop();
});
};
navigator.mediaDevices.getUserMedia({ audio: true, video: false })
.then(initalizeRecorder);
render() {
return (
<section>
<button id="start">Record</button>
<button id='stop'>Stop</button>
</section>
);
}
}
export default Record;
googletranscribe.jsx
import axios from 'axios';
const googleTranscribe = async (audioBlob) => {
const apiUrl = "http://localhost:8080/api/google-transcribe";
const url = encodeURI(apiUrl);
// Send blob to the server
const formData = new FormData();
formData.append('file', audioBlob, 'blobby.wav');
var config = {
method: 'post',
url: url,
headers: { "Content-Type": "multipart/form-data" },
data : formData,
};
axios(config)
.then(function (res) {
console.log('AXIOS success');
console.log(res);
return res.data;
})
.catch(function (err) {
console.log('AXIOS error');
console.log(err.message);
return 'AXIOS we found an error';
});
}
export default googleTranscribe;
【问题讨论】:
-
尽管尝试使用
async/await,但您没有使用await而不是.then()。因此你的return不起作用 -
你应该
return axios(config).then...,它会返回承诺。
标签: javascript reactjs async-await promise