需求:輸入一段文字,點擊語音框,將本地語音(提前準備好的) 播放出來
播放中效果
代碼
<div class="listConAI" @click="handleOpenSpeech" ><imgsrc="../../../../assets/images/blueopen.png" class="blueopenIcon" ><img:src="openVoice == true ? voiceUrl : voiceDefalutUrl" class="voiceIcon" ><audio@ended="onAudioEnded"ref="audio":src="voicePath"controlshidden="true"></audio></div>
tips: 因為我這個語音條要自定義樣式,所以給audio使用了 隱藏屬性哈~
<script setup>
import { useI18n } from 'vue-i18n';
import { ref,nextTick } from 'vue'
const loading = ref(false)
const openVoice = ref(false)
const voiceDefalutUrl = require('../../../../assets/images/openVoice.png');
const voiceUrl = require('../../../../assets/images/voice.gif');
const audio = ref(new Audio())
const voicePath = ref('')
const handleOpenSpeech = () => {openVoice.value = true// 本地鏈接voicePath.value = new URL(require('../../../../assets/music/success.mp3'), import.meta.url).hrefnextTick(() => {console.log(audio.value, 'audio')audio.value?.play()})
}
//監聽語音播放完成方法,將語音條圖片顯示狀態修改回來
const onAudioEnded = () => {openVoice.value = false
};
</script>
Tips: 如果播放語音組件在 列表
頁面中使用 播放語音方法 要適當修改
例子:
<div class="listConAI" @click="handleOpenSpeech(item.msg)" ><imgsrc="../../../assets/images/blueopen.png"class="blueopenIcon"><img:src="openVoice == true ? voiceUrl : voiceDefalutUrl"class="voiceIcon"><audioref="audio":src="voicePath"controlshidden="true"></audio></div>
const handleOpenSpeech = (value) => {openVoice.value = !openVoice.value// 本地鏈接voicePath.value = new URL(value, import.meta.url).hrefnextTick(() => {console.log(audio.value, 'audio')audio.value[0]?.play()})
}