/**
 * 语音播报
 */

import { get } from './axios'

const synth = window.speechSynthesis
const speech = new SpeechSynthesisUtterance()
let isLocalServe

setTimeout(() => {
  let voices = speechSynthesis.getVoices()
  console.log(voices)
  isLocalServe = voices.some(
    (item) => item.lang == 'zh-CN' && item.localService
  )
  if (isLocalServe) {
    speech.pitch = 2 // 获取并设置话语的音调(值越大越尖锐,越低越低沉)

    speech.rate = 3 // 获取并设置说话的速度(值越大语速越快,越小语速越慢)

    // speech.voice = 10 // 获取并设置说话的声音

    speech.volume = 1 // 获取并设置说话的音量

    speech.lang = 'zh-CN' // 设置播放语言，测试没效果
  }
}, 0)
let token = ''
let expireTime = sessionStorage.getItem('aliYunTokenExpireTime')
if (
  expireTime &&
  new Date().getTime() < new Date(Number(expireTime)).getTime()
) {
  token = sessionStorage.getItem('aliYunToken')
} else {
  get('home/getAliYunToken', {}).then((res) => {
    console.log(res)
    if (res.message) {
      token = res.data.token
      let expireTime = res.data.expireTime
      sessionStorage.setItem('aliYunTokenExpireTime', expireTime * 1000)
      sessionStorage.setItem('aliYunToken', token)
    }
  })
}

export function speak(text) {
  if (isLocalServe) {
    console.log('isLocalServe')
    speech.text = text
    synth.speak(speech)
  } else {
    console.log('Audio')
    try {
      new Audio(
        `https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/tts?speech_rate=300&appkey=B4PZmmipkz4wPqnT&token=${token}&text=${text}&format=mp3&sample_rate=16000`
      ).play()
    } catch (error) {
      console.log(error)
    }
  }
}
