<template>
    <div class="container">

        <div class="container-box">
            <div class="titbox">
                <h2 class="font-ui">语音识别</h2>
            </div>

            <div class="audio-box">
                <div>
                    <!-- <h3>录音时长：<span v-if="recorder.duration">{{recorder.duration.toFixed(4)}}</span></h3> -->

                    <el-button type="primary" plain @click="handleStart">开始录音</el-button>
                    <el-button type="info" plain @click="handlePause">暂停录音</el-button>
                    <el-button type="success" plain @click="handleResume">继续录音</el-button>
                    <el-button type="warning" plain @click="handleStop">停止录音</el-button>
                </div>

                <div style="padding-top: 10px;">
                    <!-- <h3>播放时长：
                        <span v-if="recorder.duration && playTime">{{recorder&&(playTime>recorder.duration?recorder.duration.toFixed(4):playTime.toFixed(4))}}</span>
                    </h3> -->

                    <el-button type="primary" plain @click="handlePlay">播放录音</el-button>
                    <el-button type="info" plain @click="handlePausePlay">暂停播放</el-button>
                    <el-button type="success" plain @click="handleResumePlay">继续播放</el-button>
                    <el-button type="warning" plain @click="handleStopPlay">停止播放</el-button>
                </div>

            </div>

            <div style="margin: 20px">
                <el-button  type="primary" @click="uploadRecord(1)">开始识别</el-button>
                <el-button  type="primary" @click="uploadRecord(2)">录音下载</el-button>
            </div>

            <div class="voice-box">
                <span>选择文件:</span>
                <div class="vfile" @click="cleartxt">
                    <myUpload @uploadBack="uploadBack" :fileInfo="fileInfo" :fileList="fileInfo.fileList"></myUpload>
                </div>
            </div>
            <div class="voice-box">
                <span>识别结果:</span>
                <div class="vtxt">{{voice}}</div>
            </div>
        </div>
    </div>
</template>
<script>
    import myUpload from "../../../components/upload";
    import Recorder from 'js-audio-recorder'

    export default {
        components: {
            myUpload
        },
        data() {
            return {
                fileInfo: {
                    limit: 1,
                    type: 'voice',
                    url: '/market/nlp/recognition',
                    fileList: []
                },
                voice: '',
                recorder: null,
                playTime: null,
                uploadRecordModal:false,
            }
        },
        methods: {
            cleartxt(){
                this.voice = '';
                this.fileInfo.fileList = [];
            },
            uploadBack(v) {
                this.voice = '';
                let voice = JSON.parse(v.body);
                for (let i = 0; i < voice.length; i++) {
                    this.voice += voice[i];
                }
            },
            // 开始录音
            handleStart() {
                this.recorder = new Recorder()
                Recorder.getPermission().then(() => {
                    console.log('开始录音')
                    this.recorder.start() // 开始录音
                }, (error) => {
                    this.$Message.info('请先允许该网页使用麦克风')
                    console.log(`${error.name} : ${error.message}`)
                })
            },
            handlePause() {
                console.log('暂停录音')
                this.recorder.pause() // 暂停录音
            },
            handleResume() {
                console.log('恢复录音')
                this.recorder.resume() // 恢复录音
            },
            handleStop() {
                console.log(this.recorder)
                this.recorder.stop() // 停止录音
            },
            handlePlay() {
                console.log('播放录音')
                this.recorder.play() // 播放录音

                // 播放时长
                this.timer = setInterval(() => {
                    try {
                        this.playTime = this.recorder.getPlayTime()
                    } catch (error) {
                        this.timer = null
                    }
                }, 100)
            },
            handlePausePlay() {
                console.log('暂停播放')
                this.recorder.pausePlay() // 暂停播放

                // 播放时长
                this.playTime = this.recorder.getPlayTime()
                this.time = null
            },
            handleResumePlay() {
                console.log('恢复播放')
                this.recorder.resumePlay() // 恢复播放

                // 播放时长
                this.timer = setInterval(() => {
                    try {
                        this.playTime = this.recorder.getPlayTime()
                    } catch (error) {
                        this.timer = null
                    }
                }, 100)
            },
            handleStopPlay() {
                console.log('停止播放')
                this.recorder.stopPlay() // 停止播放

                // 播放时长
                this.playTime = this.recorder.getPlayTime()
                this.timer = null
            },
            handleDestroy() {
                console.log('销毁实例')
                this.recorder.destroy() // 毁实例
                this.timer = null
            },
            uploadRecord(v) {
                if (this.recorder == null || this.recorder.duration === 0) {
                    this.$Message.error('请先录音')
                    return false
                }
                this.recorder.pause() // 暂停录音
                this.timer = null
                console.log('上传录音') // 上传录音
                var formData = new FormData()
                var blob = this.recorder.getWAVBlob() //获取wav格式音频数据
                //此处获取到blob对象后需要设置fileName满足当前项目上传需求，其它项目可直接传把blob作为file塞入formData
                var newbolb = new Blob([blob], {
                    type: 'audio/wav'
                })
                var fileOfBlob = new File([newbolb], new Date().getTime() + '.wav')
                formData.append('file', fileOfBlob);

                if(v == 1){
                    this.voice = '正在识别。。。';
                    this.uploadExcel(formData)
                }else{
                    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                        let newbolb = new Blob([blob], {
                            type: 'audio/wav'
                        })
                        window.navigator.msSaveOrOpenBlob(newbolb, new Date().getTime() + '.wav');
                    } else {
                        /* 火狐谷歌的文件下载方式 */
                        let newbolb = new Blob([blob], {
                            type: 'audio/wav'
                        })
                        var downloadElement = document.createElement('a')
                        var href = window.URL.createObjectURL(newbolb);
                        downloadElement.href = href;
                        downloadElement.download = new Date().getTime() + '.wav';
                        document.body.appendChild(downloadElement);
                        downloadElement.click();
                        document.body.removeChild(downloadElement);
                        window.URL.revokeObjectURL(href);
                    }
                }
            },
            uploadExcel(query) {
                let _this = this;
                this.$http({
                    url: '/market/nlp/recognition',
                    method: "post",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    data: query,
                }).then((res) => {
                    this.voice = '';
                    let voice = JSON.parse(res.data.body);
                    for (let i = 0; i < voice.length; i++) {
                        this.voice += voice[i];
                    }
                });
            }

        },
        mounted() {

        },
        created() {
            this.recorder = new Recorder()
        }
    }
</script>
<style scoped lang="scss">
    .audio-box{
        font-size:14px;
        padding-left: 20px;
        div{
            display: inline-block;
            width: 50%;
            // margin-right: 40px;
        }
        h3{
            margin: 10px;
        }
    }
    .titbox {
        padding-bottom: 20px;
    }

    .voice-box {
        margin-top: 30px;
        padding-right: 20px;

        span {
            width: 100px;
            display: inline-block;
            vertical-align: top;
            text-align: right;
        }

        .vfile {
            display: inline-block;
            width: calc(100% - 100px);
        }

        .vtxt {
            margin: 0 20px;
            padding: 20px;
            display: inline-block;
            width: calc(100% - 140px);
            border: 2px dotted #ddd;
            border-radius: 5px;
        }
    }
</style>
