reactjs - 音频到 blob 和 POST 到 cloudinary 问题
问题描述
我是编码新手,我正在练习一个小项目。这个想法是记录用户的音频并将其发布到 cloudinary。我可以用这段代码记录
const audioType = 'audio/webm'
async startRecording(e) {
e.preventDefault()
const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
this.audio.srcObject = stream
this.mediaRecorder = new MediaRecorder(stream, {
mimeType: audioType,
})
this.chunks = []
this.mediaRecorder.ondataavailable = e => {
if (e.data && e.data.size > 0) {
this.chunks.push(e.data)
}
}
this.chunks = []
this.mediaRecorder.start(10)
this.setState({ recording: true })
}
要停止录制,请使用以下代码更新状态并触发保存:
stopRecording(e) {
e.preventDefault()
this.mediaRecorder.stop()
this.setState({ recording: false })
this.saveAudio()
}
我保存文件,以便可以在浏览器上显示它,我制作了一个 blob:
saveAudio() {
const audioBlob = new Blob(this.chunks, { type: audioType })
const audioURL = window.URL.createObjectURL(audioBlob)
const audios = this.state.audios.concat([audioURL])
this.setState({ audios })
this.handleUpload()
}
最后是问题,上传功能到cloudinary:
async handleUpload () {
const data = new FormData()
data.append('audio', this.audioBlob)
data.append('upload_preset', uploadPreset)
try {
const res = await axios.post(uploadUrl, data)
this.setState({
audioStatePath: res.data.secure_url,
})
console.log(res.data.secure_url)
} catch (err) {
console.log(err)
}
}
几天来我一直在寻找解决方案,尝试其他代码并寻找其他人的帖子。它类似于这里讨论的问题 Uploading Audio to Cloudinary
唯一的区别是我不理解该代码。很抱歉已经提出问题,但一开始很难......谢谢
解决方案
推荐阅读
- selenium - Selenium webdriver 在亚马逊中找不到添加到购物车按钮
- discord - Discord Bot - 将总反应限制为 1
- list - 如何创建页面列表并立即导航到不同页面
- r - 如何从 R Studio 中的数据框中删除大量文本
- python - 在文件系统中找不到 python 的标准库
- reactjs - useState 未正确更新数组
- c# - Unity3D使用法线向量面对世界中的物体
- mysql - 我想在执行 sql 之前提供附加条件
- c++ - 永远不要通知 CListCtrl 的 CHeaderCtrl 的 HDN_TRACK 消息
- c# - 将文本框中给定的 ASCII 文本转换为另一个字符串中的十六进制格式