代码之家  ›  专栏  ›  技术社区  ›  CuriousProgrammer70184

如何修复问题音频播放()?

  •  0
  • CuriousProgrammer70184  · 技术社区  · 6 年前

    我正在尝试使用JavaScript音频对象。我非常严格地遵循本指南: https://medium.com/@bryanjenningz/how-to-record-and-play-audio-in-javascript-faa1b2b3e49b .

    在第6部分中,我应该对一个音频对象调用play(),但是我收到一个错误,它显示“uncaughttypeerror:音频播放“不是一个函数”,我不确定我在做什么不正确。有什么帮助吗?

    import React, { Component } from 'react'
    
    class Audio extends Component {
    
      constructor() {
        super();
        this.state = {
          showButton: true,
        };
      }
    
      recordAudio = () => {
        this.setState({ showButton: false })
    
        navigator.mediaDevices.getUserMedia({ audio: true })
        .then(stream => {
          this.setState({ mediaRecorder: new MediaRecorder(stream) })
          this.state.mediaRecorder.start();
    
          const audioChunks = [];
    
          this.state.mediaRecorder.addEventListener("dataavailable", event => {
            audioChunks.push(event.data);
          });
    
          this.state.mediaRecorder.addEventListener("stop", () => {
            const audioBlob = new Blob(audioChunks);
            const audioUrl = URL.createObjectURL(audioBlob);
            const audio = new Audio(audioUrl);
            console.log(audio);
            audio.play();
          });
        });
      }
    
      stopRecording = () => {
        this.setState({ showButton: true })
        this.state.mediaRecorder.stop();
      }
    
      render() {
        return (
          <div>
    
          {/* This is a ternary operator that changes the button that is shown  */}
          {
            this.state.showButton ?
            <button type="button" onClick={this.recordAudio}> Start Recording </button> :
            <button type="button" onClick={this.stopRecording}> Stop Recording </button>
          }
    
          </div>
    
        )
      }
    
    }
    
    export default Audio;
    

    编辑:控制台.log(音频)输出:

    Audio {props: undefined, context: undefined, refs: {…}, updater: {…}, recordAudio: ƒ, …}
        context:undefined
        props:undefined
        recordAudio:ƒ ()
        refs:{}
        state:{showButton: true}
        stopRecording:ƒ ()
        updater:{isMounted: ƒ, enqueueForceUpdate: ƒ, enqueueReplaceState: ƒ, enqueueSetState: ƒ}
        isMounted:(...)
        replaceState:(...)
        __proto__:ReactComponent
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   CuriousProgrammer70184    6 年前

    凯伊多的评论为我解决了这个问题。因为我把我的类命名为“Audio”并调用“Audio”构造函数(当我以为我在调用窗口。音频),它没有创建适当的对象。

    根据他们的解决方案,要么重命名类,调用窗口。音频,或调用默认值窗口。音频功能如他们的评论所述。

    推荐文章