JavaScript录音功能-react

实现网页版录音功能,不支持IE浏览器

index.html

        // 获取录音权限
        window.onload = function init() {
            try {
                window.AudioContext = window.AudioContext || window.webkitAudioContext;
                navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia;
                window.URL = window.URL || window.webkitURL;
                audio_context = new AudioContext;
            } catch (e) {
                alert('No web audio support in this browser!');
            }   
        };

record.jsx

let recorder;
let audio_context;
import { Recorder } from 'utils';
export default class Record extends BaseComponent {
    constructor(props) {
        super(props);
        this.state = {
        }

    }
    componentDidMount(){
        let getUserMedia_1 = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia)
        getUserMedia_1.call(navigator,{audio: true}, this.startUserMedia, function(e) {
            console.log('No live audio input: ' + e)
        });

    }
    // 初始化录音功能
    startUserMedia = (stream) => {
        audio_context = new AudioContext
        var input = audio_context.createMediaStreamSource(stream)
        recorder = new Recorder(input)
    }
    // 开始录音
    startRecording = () => {
        recorder && recorder.record()
    }
    // 停止录音
    stopRecording = () => {
        recorder && recorder.stop()
        this.createDownloadLink()
        recorder.clear() // 清楚录音,如果不清除,可以继续录音
    }
    // 生成文件
    createDownloadLink = () => {
        recorder && recorder.exportWAV((blob) => {
            console.log(blob)
            this.setState({
                fileDataBlob: blob
            })
            if(!blob){
                console.log('无录音文件')
                return false;
            }else{
                var url = URL.createObjectURL(blob); // 生成的录音文件路径,可直接播放
            }
        });
    }
}

最后还要引入recorder.js
我的引入方法:将recorder.js放入utils中
utils/index.js

export { default as Recorder } from './recorder';

你可能感兴趣的:(JavaScript录音功能-react)