如何解决audio.play()的问题?

时间:2018-08-23 19:27:54

标签: javascript html audio uncaught-typeerror

我正在尝试使用JavaScript Audio对象。我正在密切关注本指南:https://medium.com/@bryanjenningz/how-to-record-and-play-audio-in-javascript-faa1b2b3e49b

在第6部分中,我应该在Audio对象上调用play(),但是我收到一条错误消息,提示“未捕获的TypeError:audio.play不是函数”,并且我不确定自己在做什么错误。有帮助吗?

编辑:到目前为止的代码:

static void UnhandledExceptionHandler (object source, UnhandledExceptionEventArgs e)
            {
                logger.Error ("Message:" + ((Exception) e.ExceptionObject) .Message);
                var st = new StackTrace (((Exception) e.ExceptionObject), true);
                for (int i = 0; i <st.FrameCount; i ++)
                {
                    var frame = st.GetFrame (i);
                    var method = frame.GetMethod ();
                    // if (method.DeclaringType.FullName.Contains ("AMT"))
                    {
                        logger.Error ("Source:" + method.DeclaringType.FullName + "." + method.Name);
                        logger.Error ("Line:" + frame.GetFileLineNumber ());
                    }
                }
            }

编辑:console.log(音频)输出:

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;

1 个答案:

答案 0 :(得分:1)

Kaiido的评论为我解决了这个问题。因为我已经将类命名为“ Audio”并调用了“ Audio”构造函数(当我以为我正在调用window.Audio时),所以它没有创建适当的对象。

根据他们的解决方案,重命名该类,调用window.Audio或调用默认window.Audio功能,如其注释中所述。