录制音频然后播放

时间:2021-01-06 12:18:56

标签: javascript vue.js

我正在使用 vue.js 并且我在我的网页上创建了 5 种不同的声音,用户可以打开/关闭声音并创建混合声音。 现在我正在尝试录制用户播放的混音然后播放。

请告知如何实现这个或我的代码有什么问题,任何建议将不胜感激。

谢谢

<template>
        <a class="rightButton"  @click="record" v-if="!startRecord">
        <div>record</div>
        </a>

        <a class="rightButton"  @click="record" v-if="startRecord">
        <div>stop</div>
        </a>

        <audio controls id="recorder"></audio>
        </div>

</template>

<script>
export default {
    data(){
        return{
            chunks:undefined,
            ac: undefined,
            osc: undefined,
            dest: undefined,
            mediaRecorder:undefined,
            startRecord : false
        }
    },
    methods:{
        record(){
            this.startRecord = !this.startRecord
            console.log(this.startRecord);
            if(this.startRecord){
                this.mediaRecorder.start();
                this.osc.start(0)
                console.log("start recorder: "  + this.mediaRecorder);
                
            }else{
                this.mediaRecorder.stop();
                this.osc.stop(0);
                console.log(this.mediaRecorder);
            }

        }
    },
    created(){
            this.ac = new AudioContext()
            this.osc = this.ac.createOscillator()
            this.dest = this.ac.createMediaStreamDestination()
            this.mediaRecorder = new MediaRecorder(this.dest.stream)
            this.osc.connect(this.dest);
    },
    watch:{
        mediaRecorder(){
            this.mediaRecorder.ondataavailable = function(event) {
                console.log("Blob event: ");
                console.log(event.data);
                this.chunks = []
                this.chunks.push(event.data);
                console.log("chunks: ");
                console.log(this.chunks);
        }

        this.mediaRecorder.onstop = function() {
       var blob = new Blob(this.chunks, { 'type' : 'audio/ogg; codecs=opus' });
       document.querySelector("audio").src = URL.createObjectURL(blob);
     };
    }
    }
}
</script>

0 个答案:

没有答案