vue 百度智能语音引入

voicePrompt.js

import Cookies from 'js-cookie'
import axios from 'axios'
const client_id='你的api_key'
const client_secret='你的api_secret'
function gettoken() {
    try {
        const url = `baidu/oauth/2.0/token?grant_type=client_credentials&client_id=${client_id}&client_secret=${client_secret}`
        axios
            .post(url)
            .then(async res => {
                const { access_token } = res.data
                Cookies.set('access_token', access_token, { expires: 30 })
            })
            .catch(error => {})
    } catch ({ response }) {
        console.info('登录异常')
    }
}

function voicePrompt(text) {
    const token = Cookies.get('access_token')
    if (token) {
        new Audio(`voice/text2audio?tok=${token}&cuid=shibalizhiwai&lan=zh&per=1&ctp=1&tex=${text}`).play()
    } else {
        gettoken()
    }
}
if (!Cookies.get('access_token')) {
    gettoken()
}

export { voicePrompt }

main.js引入

import * as voicePromptFun from '@/utils/voicePrompt'

Vue.prototype.voicePrompt = voicePromptFun.voicePrompt

组件中使用

this.voicePrompt( '你长的真好看!!!')

你可能感兴趣的:(vue 百度智能语音引入)