npx create-react-app audiorecorder
npm i vmsg
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
import React from "react"; import vmsg from "vmsg"; const recorder = new vmsg.Recorder({ wasmURL: "https://unpkg.com/vmsg@0.3.0/vmsg.wasm" }); class App extends React.Component { state = { isLoading: false, isRecording: false, recordings: [] }; record = async () => { this.setState({ isLoading: true }); if (this.state.isRecording) { const blob = await recorder.stopRecording(); this.setState({ isLoading: false, isRecording: false, recordings: this.state.recordings.concat(URL.createObjectURL(blob)) }); } else { try { await recorder.initAudio(); await recorder.initWorker(); recorder.startRecording(); this.setState({ isLoading: false, isRecording: true }); } catch (e) { console.error(e); this.setState({ isLoading: false }); } } }; render() { const { isLoading, isRecording, recordings } = this.state; return ( <React.Fragment> <button disabled={isLoading} onClick={this.record}> {isRecording ? "Stop" : "Record"} </button> <ul style={{ listStyle: "none", padding: 0 }}> {recordings.map(url => ( <li key={url}> <audio src={url} controls /> </li> ))} </ul> </React.Fragment> ); } } export default App; |