简体   繁体   中英

How to fix issue with audio.play()?

I am trying to use the JavaScript Audio object. I am following this guide very closely: https://medium.com/@bryanjenningz/how-to-record-and-play-audio-in-javascript-faa1b2b3e49b .

In part 6, I am supposed to call play() on an Audio object, but I am receiving an error that says "Uncaught TypeError: audio.play is not a function" and I am unsure what I am doing incorrectly. Any help?

Edit: Code so far:

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;

Edit: console.log(audio) output:

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

Kaiido's comment solved the issue for me. Since I had named my class "Audio" and was calling the "Audio" constructor (when I thought I was calling window.Audio), it was not creating the appropriate object.

As per their solution, either rename the class, call window.Audio, or call the default window.Audio functionality as detailed in their comment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM