gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 01:16:28 24 4
gpt4 key购买 nike

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

在第 6 部分中,我应该在 Audio 对象上调用 play(),但我收到一条错误,提示“未捕获的类型错误: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 功能,如他们的评论中所述。

关于javascript - 如何解决 audio.play() 的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51993011/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com