最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

基于Vue2實現(xiàn)語音報警功能的示例代碼

 更新時間:2025年11月27日 08:23:12   作者:IT界Tony哥  
Vue2 實現(xiàn)消息語音報警功能 下面是一個完整的Vue2消息語音報警實現(xiàn)方案,包含多種語音播報方式和自定義配置。 1. 安裝依賴 2. 語音報警組件 核心語音服務類 Vue2語音報警組件 3. 全局事

下面是一個完整的Vue2消息語音報警實現(xiàn)方案,包含多種語音播報方式和自定義配置。

1. 安裝依賴

npm install speakingurl
# 或使用更輕量的方案
npm install vue-speech --save

2. 語音報警組件

核心語音服務類

// src/utils/voiceAlert.js
class VoiceAlert {
  constructor() {
    this.synth = window.speechSynthesis;
    this.isSupported = !!this.synth;
    this.isSpeaking = false;
    this.utterance = null;
    this.volume = 1;
    this.rate = 1;
    this.pitch = 1;
    this.voice = null;
    
    this.init();
  }

  init() {
    if (!this.isSupported) {
      console.warn('瀏覽器不支持語音合成API');
      return;
    }

    // 加載可用語音列表
    this.loadVoices();
    
    // 語音列表加載事件
    speechSynthesis.addEventListener('voiceschanged', () => {
      this.loadVoices();
    });
  }

  loadVoices() {
    this.voices = this.synth.getVoices();
    // 優(yōu)先選擇中文語音
    const chineseVoice = this.voices.find(voice => 
      voice.lang.includes('zh') || voice.lang.includes('CN')
    );
    this.voice = chineseVoice || this.voices[0];
  }

  // 播報警報消息
  alert(message, options = {}) {
    if (!this.isSupported) return false;

    // 停止當前播報
    this.stop();

    this.utterance = new SpeechSynthesisUtterance(message);
    
    // 設置參數(shù)
    this.utterance.volume = options.volume || this.volume;
    this.utterance.rate = options.rate || this.rate;
    this.utterance.pitch = options.pitch || this.pitch;
    this.utterance.voice = options.voice || this.voice;
    this.utterance.lang = options.lang || 'zh-CN';

    // 事件監(jiān)聽
    this.utterance.onstart = () => {
      this.isSpeaking = true;
      options.onStart && options.onStart();
    };

    this.utterance.onend = () => {
      this.isSpeaking = false;
      options.onEnd && options.onEnd();
    };

    this.utterance.onerror = (error) => {
      this.isSpeaking = false;
      console.error('語音播報錯誤:', error);
      options.onError && options.onError(error);
      
      // 降級方案:嘗試使用音頻文件
      if (options.fallbackAudio) {
        this.playAudioFallback(options.fallbackAudio);
      }
    };

    this.synth.speak(this.utterance);
    return true;
  }

  // 播放音頻文件降級方案
  playAudioFallback(audioUrl) {
    const audio = new Audio(audioUrl);
    audio.play().catch(error => {
      console.error('音頻播放失敗:', error);
    });
  }

  // 停止播報
  stop() {
    if (this.isSpeaking) {
      this.synth.cancel();
      this.isSpeaking = false;
    }
  }

  // 暫停播報
  pause() {
    if (this.isSpeaking) {
      this.synth.pause();
    }
  }

  // 恢復播報
  resume() {
    if (this.synth.paused) {
      this.synth.resume();
    }
  }

  // 設置語音參數(shù)
  setVoiceParams(params) {
    if (params.volume !== undefined) this.volume = params.volume;
    if (params.rate !== undefined) this.rate = params.rate;
    if (params.pitch !== undefined) this.pitch = params.pitch;
    if (params.voice !== undefined) this.voice = params.voice;
  }

  // 獲取可用語音列表
  getVoices() {
    return this.voices || [];
  }

  // 檢查瀏覽器支持情況
  checkSupport() {
    return this.isSupported;
  }
}

// 創(chuàng)建單例
const voiceAlert = new VoiceAlert();
export default voiceAlert;

Vue2語音報警組件

<!-- src/components/VoiceAlert.vue -->
<template>
  <div class="voice-alert">
    <!-- 語音控制面板 -->
    <div v-if="showControl" class="voice-control-panel">
      <div class="control-item">
        <label>音量:</label>
        <input 
          type="range" 
          min="0" max="1" step="0.1" 
          v-model="volume"
          @change="updateVoiceParams"
        >
        <span>{{ (volume * 100).toFixed(0) }}%</span>
      </div>
      
      <div class="control-item">
        <label>語速:</label>
        <input 
          type="range" 
          min="0.1" max="2" step="0.1" 
          v-model="rate"
          @change="updateVoiceParams"
        >
        <span>{{ rate }}</span>
      </div>
      
      <div class="control-item">
        <label>音調(diào):</label>
        <input 
          type="range" 
          min="0.1" max="2" step="0.1" 
          v-model="pitch"
          @change="updateVoiceParams"
        >
        <span>{{ pitch }}</span>
      </div>
      
      <div class="control-item">
        <label>語音:</label>
        <select v-model="selectedVoice" @change="updateVoiceParams">
          <option 
            v-for="voice in availableVoices" 
            :key="voice.name" 
            :value="voice"
          >
            {{ voice.name }} ({{ voice.lang }})
          </option>
        </select>
      </div>
    </div>

    <!-- 報警消息列表 -->
    <div class="alert-list">
      <div 
        v-for="alert in recentAlerts" 
        :key="alert.id"
        :class="['alert-item', alert.type]"
      >
        <div class="alert-content">
          <span class="alert-time">{{ formatTime(alert.timestamp) }}</span>
          <span class="alert-message">{{ alert.message }}</span>
        </div>
        <div class="alert-actions">
          <button @click="speakAlert(alert)">??</button>
          <button @click="removeAlert(alert.id)">×</button>
        </div>
      </div>
    </div>

    <!-- 控制按鈕 -->
    <div class="control-buttons">
      <button @click="toggleControl">
        {{ showControl ? '隱藏設置' : '語音設置' }}
      </button>
      <button @click="stopSpeaking" :disabled="!isSpeaking">
        停止播報
      </button>
      <button @click="clearAlerts">清空消息</button>
      <button @click="testVoice">測試語音</button>
    </div>

    <!-- 瀏覽器支持提示 -->
    <div v-if="!isSupported" class="browser-warning">
      ?? 您的瀏覽器不支持語音合成功能,請使用Chrome、Edge等現(xiàn)代瀏覽器
    </div>
  </div>
</template>

<script>
import voiceAlert from '@/utils/voiceAlert'

export default {
  name: 'VoiceAlert',
  props: {
    // 最大保存消息數(shù)量
    maxAlerts: {
      type: Number,
      default: 50
    },
    // 自動播報新消息
    autoSpeak: {
      type: Boolean,
      default: true
    },
    // 顯示控制面板
    showControlPanel: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isSupported: false,
      isSpeaking: false,
      showControl: this.showControlPanel,
      volume: 1,
      rate: 1,
      pitch: 1,
      selectedVoice: null,
      availableVoices: [],
      recentAlerts: [],
      alertCounter: 0
    }
  },
  mounted() {
    this.isSupported = voiceAlert.checkSupport();
    if (this.isSupported) {
      this.availableVoices = voiceAlert.getVoices();
      this.selectedVoice = this.availableVoices[0] || null;
      this.updateVoiceParams();
    }

    // 監(jiān)聽全局報警消息
    this.$eventBus.$on('voice-alert', this.handleNewAlert);
  },
  beforeDestroy() {
    this.$eventBus.$off('voice-alert', this.handleNewAlert);
    voiceAlert.stop();
  },
  methods: {
    // 處理新報警消息
    handleNewAlert(alertData) {
      const alert = {
        id: ++this.alertCounter,
        message: alertData.message,
        type: alertData.type || 'info',
        timestamp: new Date(),
        priority: alertData.priority || 1
      };

      // 添加到消息列表
      this.recentAlerts.unshift(alert);
      
      // 限制消息數(shù)量
      if (this.recentAlerts.length > this.maxAlerts) {
        this.recentAlerts = this.recentAlerts.slice(0, this.maxAlerts);
      }

      // 自動播報
      if (this.autoSpeak && this.isSupported) {
        this.speakAlert(alert);
      }
    },

    // 播報警報消息
    speakAlert(alert) {
      const message = this.formatAlertMessage(alert);
      
      voiceAlert.alert(message, {
        volume: this.volume,
        rate: this.rate,
        pitch: this.pitch,
        voice: this.selectedVoice,
        onStart: () => {
          this.isSpeaking = true;
        },
        onEnd: () => {
          this.isSpeaking = false;
        },
        onError: (error) => {
          this.isSpeaking = false;
          console.error('語音播報失敗:', error);
          this.$notify.error('語音播報失敗');
        }
      });
    },

    // 格式化報警消息
    formatAlertMessage(alert) {
      const prefixes = {
        error: '緊急報警:',
        warning: '警告:',
        info: '通知:',
        success: '正常:'
      };
      
      const prefix = prefixes[alert.type] || '';
      return prefix + alert.message;
    },

    // 停止播報
    stopSpeaking() {
      voiceAlert.stop();
      this.isSpeaking = false;
    },

    // 更新語音參數(shù)
    updateVoiceParams() {
      voiceAlert.setVoiceParams({
        volume: this.volume,
        rate: this.rate,
        pitch: this.pitch,
        voice: this.selectedVoice
      });
    },

    // 移除報警消息
    removeAlert(alertId) {
      this.recentAlerts = this.recentAlerts.filter(alert => alert.id !== alertId);
    },

    // 清空所有消息
    clearAlerts() {
      this.recentAlerts = [];
    },

    // 切換控制面板顯示
    toggleControl() {
      this.showControl = !this.showControl;
    },

    // 測試語音
    testVoice() {
      this.handleNewAlert({
        message: '這是一條測試語音消息,當前語音設置正常。',
        type: 'info'
      });
    },

    // 格式化時間
    formatTime(timestamp) {
      return timestamp.toLocaleTimeString('zh-CN', {
        hour12: false,
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    }
  }
}
</script>

<style scoped>
.voice-alert {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 16px;
  background: #fafafa;
  max-width: 600px;
  margin: 0 auto;
}

.voice-control-panel {
  background: white;
  padding: 16px;
  border-radius: 4px;
  margin-bottom: 16px;
  border: 1px solid #ddd;
}

.control-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.control-item label {
  width: 60px;
  font-weight: bold;
}

.control-item input[type="range"] {
  flex: 1;
  margin: 0 8px;
}

.alert-list {
  max-height: 300px;
  overflow-y: auto;
  margin-bottom: 16px;
}

.alert-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  margin-bottom: 4px;
  border-radius: 4px;
  background: white;
  border-left: 4px solid #ccc;
}

.alert-item.error {
  border-left-color: #f44336;
  background: #ffebee;
}

.alert-item.warning {
  border-left-color: #ff9800;
  background: #fff3e0;
}

.alert-item.info {
  border-left-color: #2196f3;
  background: #e3f2fd;
}

.alert-item.success {
  border-left-color: #4caf50;
  background: #e8f5e8;
}

.alert-content {
  flex: 1;
}

.alert-time {
  font-size: 12px;
  color: #666;
  margin-right: 8px;
}

.alert-actions button {
  background: none;
  border: none;
  cursor: pointer;
  margin-left: 4px;
  padding: 4px;
}

.control-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.control-buttons button {
  padding: 8px 16px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
}

.control-buttons button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.browser-warning {
  background: #fff3cd;
  border: 1px solid #ffeaa7;
  color: #856404;
  padding: 12px;
  border-radius: 4px;
  margin-top: 16px;
}
</style>

3. 全局事件總線配置

// src/utils/eventBus.js
import Vue from 'vue';

// 創(chuàng)建事件總線
export const eventBus = new Vue();

// 在main.js中全局注冊
// import { eventBus } from './utils/eventBus';
// Vue.prototype.$eventBus = eventBus;

4. 使用示例

<!-- src/views/Dashboard.vue -->
<template>
  <div class="dashboard">
    <h1>系統(tǒng)監(jiān)控面板</h1>
    
    <!-- 語音報警組件 -->
    <voice-alert 
      :auto-speak="true"
      :max-alerts="30"
      ref="voiceAlert"
    />

    <!-- 模擬報警按鈕 -->
    <div class="demo-buttons">
      <button @click="triggerTestAlert('info')">觸發(fā)信息報警</button>
      <button @click="triggerTestAlert('warning')">觸發(fā)警告報警</button>
      <button @click="triggerTestAlert('error')">觸發(fā)錯誤報警</button>
      <button @click="triggerMQTTAlert">模擬MQTT消息</button>
    </div>

    <!-- 實時數(shù)據(jù)展示 -->
    <div class="sensor-data">
      <div 
        v-for="sensor in sensorData" 
        :key="sensor.id"
        class="sensor-item"
        :class="{ 'alert': sensor.value > sensor.threshold }"
      >
        <h3>{{ sensor.name }}</h3>
        <p>數(shù)值: {{ sensor.value }}</p>
        <p>狀態(tài): {{ sensor.status }}</p>
      </div>
    </div>
  </div>
</template>

<script>
import VoiceAlert from '@/components/VoiceAlert.vue'

export default {
  name: 'Dashboard',
  components: {
    VoiceAlert
  },
  data() {
    return {
      sensorData: [
        { id: 1, name: '溫度傳感器', value: 25, threshold: 30, status: '正常' },
        { id: 2, name: '濕度傳感器', value: 60, threshold: 80, status: '正常' },
        { id: 3, name: '壓力傳感器', value: 100, threshold: 120, status: '正常' }
      ],
      mqttClient: null
    }
  },
  mounted() {
    // 模擬MQTT消息接收
    this.simulateMQTTMessages();
  },
  methods: {
    // 觸發(fā)測試報警
    triggerTestAlert(type) {
      const messages = {
        info: '系統(tǒng)運行正常,所有傳感器數(shù)據(jù)在正常范圍內(nèi)。',
        warning: '警告:溫度傳感器數(shù)值接近閾值,請關注。',
        error: '緊急報警:壓力傳感器數(shù)值超限,立即處理!'
      };

      this.$eventBus.$emit('voice-alert', {
        message: messages[type],
        type: type,
        priority: type === 'error' ? 3 : type === 'warning' ? 2 : 1
      });
    },

    // 模擬MQTT報警
    triggerMQTTAlert() {
      const alerts = [
        '檢測到設備離線:傳感器節(jié)點002',
        '數(shù)據(jù)異常:溫度突然升高5度',
        '系統(tǒng)提示:存儲空間使用率達到85%',
        '網(wǎng)絡中斷:與服務器連接丟失'
      ];
      
      const randomAlert = alerts[Math.floor(Math.random() * alerts.length)];
      const types = ['info', 'warning', 'error'];
      const randomType = types[Math.floor(Math.random() * types.length)];

      this.$eventBus.$emit('voice-alert', {
        message: randomAlert,
        type: randomType,
        priority: randomType === 'error' ? 3 : randomType === 'warning' ? 2 : 1
      });
    },

    // 模擬MQTT消息接收
    simulateMQTTMessages() {
    // 定時模擬傳感器數(shù)據(jù)更新
    setInterval(() => {
      this.sensorData.forEach(sensor => {
        // 模擬數(shù)據(jù)波動
        const change = (Math.random() - 0.5) * 10;
        sensor.value = Math.max(0, sensor.value + change);
        
        // 更新狀態(tài)
        if (sensor.value > sensor.threshold) {
          sensor.status = '超限';
          // 觸發(fā)語音報警
          this.$eventBus.$emit('voice-alert', {
            message: `${sensor.name}數(shù)值超限,當前值:${sensor.value.toFixed(1)}`,
            type: 'error',
            priority: 3
          });
        } else if (sensor.value > sensor.threshold * 0.8) {
          sensor.status = '警告';
          this.$eventBus.$emit('voice-alert', {
            message: `${sensor.name}數(shù)值接近閾值,當前值:${sensor.value.toFixed(1)}`,
            type: 'warning',
            priority: 2
          });
        } else {
          sensor.status = '正常';
        }
      });
    }, 10000); // 每10秒更新一次
  }
}
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.demo-buttons {
  margin: 20px 0;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.demo-buttons button {
  padding: 10px 20px;
  border: 1px solid #ddd;
  background: #f5f5f5;
  border-radius: 4px;
  cursor: pointer;
}

.sensor-data {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.sensor-item {
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background: white;
}

.sensor-item.alert {
  border-color: #f44336;
  background: #ffebee;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { box-shadow: 0 0 0 0 rgba(244, 67, 54, 0.4); }
  70% { box-shadow: 0 0 0 10px rgba(244, 67, 54, 0); }
  100% { box-shadow: 0 0 0 0 rgba(244, 67, 54, 0); }
}
</style>

5. 在main.js中全局配置

// src/main.js
import Vue from 'vue'
import App from './App.vue'
import { eventBus } from './utils/eventBus'

// 全局事件總線
Vue.prototype.$eventBus = eventBus

// 全局語音報警方法
Vue.prototype.$voiceAlert = function(message, options = {}) {
  eventBus.$emit('voice-alert', {
    message,
    type: options.type || 'info',
    priority: options.priority || 1
  });
}

new Vue({
  render: h => h(App),
}).$mount('#app')

主要特性

  • 多瀏覽器支持: 基于Web Speech API,支持現(xiàn)代瀏覽器
  • 可配置參數(shù): 音量、語速、音調(diào)、語音選擇
  • 消息管理: 歷史消息記錄和清理
  • 優(yōu)先級處理: 支持不同級別的報警消息
  • 降級方案: 語音合成失敗時可使用音頻文件
  • 易于集成: 可與MQTT、WebSocket等實時消息系統(tǒng)結(jié)合

這個實現(xiàn)提供了完整的語音報警功能,可以根據(jù)實際需求進行調(diào)整和擴展。

到此這篇關于基于Vue2實現(xiàn)語音報警功能的示例代碼的文章就介紹到這了,更多相關Vue2語音報警內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • 關掉vue插件Vetur格式化的時候自動添加的樣式操作

    關掉vue插件Vetur格式化的時候自動添加的樣式操作

    這篇文章主要介紹了關掉vue插件Vetur格式化的時候自動添加的樣式操作,文章圍繞主題展開操作過程,需要的小伙伴可以參考一下,希望對你有所幫助
    2022-05-05
  • vue把頁面轉(zhuǎn)換成圖片導出方式(html2canvas導出不全問題)

    vue把頁面轉(zhuǎn)換成圖片導出方式(html2canvas導出不全問題)

    這篇文章主要介紹了vue把頁面轉(zhuǎn)換成圖片導出方式(html2canvas導出不全問題),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-10-10
  • vue實現(xiàn)多條件篩選超簡潔代碼

    vue實現(xiàn)多條件篩選超簡潔代碼

    這篇文章主要給大家介紹了關于vue實現(xiàn)多條件篩選的相關資料,隨著數(shù)據(jù)的不斷增多,我們往往需要在表格中進行多條件的篩選,以便快速定位符合我們需求的數(shù)據(jù),需要的朋友可以參考下
    2023-09-09
  • vue3中使用router路由實現(xiàn)跳轉(zhuǎn)傳參的方法

    vue3中使用router路由實現(xiàn)跳轉(zhuǎn)傳參的方法

    這篇文章主要介紹了vue3中使用router路由實現(xiàn)跳轉(zhuǎn)傳參的方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-03-03
  • Vue?el-menu?左側(cè)菜單導航功能的實現(xiàn)

    Vue?el-menu?左側(cè)菜單導航功能的實現(xiàn)

    這篇文章主要介紹了Vue?el-menu?左側(cè)菜單導航功能,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-08-08
  • 使用 Element UI Table 的 slot-scope方法

    使用 Element UI Table 的 slot-scope方法

    這篇文章主要介紹了使用 Element UI Table 的 slot-scope方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-10-10
  • vue?input組件如何設置失焦與聚焦

    vue?input組件如何設置失焦與聚焦

    這篇文章主要介紹了vue?input組件如何設置失焦與聚焦,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-10-10
  • Vue項目中使用mock.js的完整步驟

    Vue項目中使用mock.js的完整步驟

    這篇文章主要給大家介紹了關于在Vue項目中使用mock.js的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-01-01
  • 淺談Vue中的this.$store.state.xx.xx

    淺談Vue中的this.$store.state.xx.xx

    這篇文章主要介紹了Vue中的this.$store.state.xx.xx用法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • vue中子組件傳遞數(shù)據(jù)給父組件的講解

    vue中子組件傳遞數(shù)據(jù)給父組件的講解

    今天小編就為大家分享一篇關于vue中子組件傳遞數(shù)據(jù)給父組件的講解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-01-01

最新評論

老河口市| 长春市| 蕲春县| 南城县| 崇文区| 龙口市| 铜梁县| 太和县| 达孜县| 禄丰县| 安顺市| 小金县| 新昌县| 湘阴县| 繁峙县| 开远市| 洱源县| 普陀区| 连平县| 敦化市| 墨竹工卡县| 寿宁县| 古田县| 婺源县| 奉节县| 杨浦区| 乡城县| 定兴县| 密云县| 汉寿县| 泉州市| 南陵县| 桐城市| 苏尼特左旗| 海阳市| 陆河县| 额尔古纳市| 晴隆县| 长沙市| 霍城县| 黑山县|