Vue中使用speak-tts插件實現點擊按鈕后進行語音播報(TTS/文字轉語音)


場景

speak-tts插件

https://www.npmjs.com/package/speak-tts

 

實現點擊按鈕觸發語音播報,播報指定的文字內容。

為什么不能實現自動語音播報。

chrome瀏覽器在18年4月起,就在桌面瀏覽器全面禁止了音視頻的自動播放功能。

嚴格地來說,是Chrome不允許在用戶對網頁進行觸發之前播放音頻。

不光是這樣,在頁面加載完畢的情況下,用戶沒有click、dbclick、touch等主動交互行為,

使用js直接調用.play() 方法的話,chrome都會拋出如下錯誤:Uncaught (in promise) DOMException;

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi
關注公眾號
霸道的程序猿
獲取編程相關電子書、教程推送與免費下載。

實現

1、參考官方說明安裝依賴

npm install speak-tts

 

 

2、在頁面中引入

import Speech from 'speak-tts'

3、聲明speech對象

  data() {
    return {
      speech: null,
    };

4、頁面加載完調用初始化方法

 mounted() {
    this.speechInit();
  },
  methods: {
    speechInit() {
      this.speech = new Speech();
      this.speech.setLanguage("zh-CN");
      this.speech.init().then(() => {});
    },

5、頁面添加按鈕

<el-button type="success" @click="speakTtsSpeech">speak-tts語音播報</el-button>

6、按鈕點擊事件中調用播放方法

    speakTtsSpeech() {
      this.speech.speak({ text: "公眾號:霸道的程序猿" }).then(() => {
        console.log("讀取成功");
      });
    },

7、完整示例代碼

<template>
  <el-button type="success" @click="speakTtsSpeech">speak-tts語音播報</el-button>
</template>
<script>
import Speech from "speak-tts"; // es6
export default {
  name: "SpeechDemo",
  data() {
    return {
      speech: null,
    };
  },
  mounted() {
    this.speechInit();
  },
  methods: {
    speakTtsSpeech() {
      this.speech.speak({ text: "公眾號:霸道的程序猿" }).then(() => {
        console.log("讀取成功");
      });
    },
    speechInit() {
      this.speech = new Speech();
      this.speech.setLanguage("zh-CN");
      this.speech.init().then(() => {});
    },
  },
};
</script>

<style scoped>
</style>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM