首页 > 解决方案 > 音频到 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

唯一的区别是我不理解该代码。很抱歉已经提出问题,但一开始很难......谢谢

标签: reactjsaudioaxiosblobcloudinary

解决方案


我能够更多地理解这个答案中的代码,最终解决了我的问题!

将音频上传到 Cloudinary

谢谢亚历山大!!!


推荐阅读