簡體   English   中英

如何解決audio.play()的問題?

[英]How to fix issue with audio.play()?

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

在第6部分中,我應該在Audio對象上調用play(),但是我收到一條錯誤消息,提示“未捕獲的TypeError:audio.play不是函數”,而且我不確定自己做錯了什么。 有什么幫助嗎?

編輯:到目前為止的代碼:

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;

編輯:console.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

Kaiido的評論為我解決了這個問題。 因為我已經將類命名為“ Audio”並調用了“ Audio”構造函數(當我以為我正在調用window.Audio時),所以它沒有創建適當的對象。

根據他們的解決方案,重命名該類,調用window.Audio或調用默認window.Audio功能,如其注釋中所述。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM