我正在尝试使用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