需求:输入一段文字,点击语音框,将本地语音(提前准备好的) 播放出来
播放中效果
代码
<div class="listConAI" @click="handleOpenSpeech" >
<img
src="../../../../assets/images/blueopen.png" class="blueopenIcon" >
<img
:src="openVoice == true ? voiceUrl : voiceDefalutUrl" class="voiceIcon" >
<audio
@ended="onAudioEnded"
ref="audio"
:src="voicePath"
controls
hidden="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).href
nextTick(() => {
console.log(audio.value, 'audio')
audio.value?.play()
})
}
//监听语音播放完成方法,将语音条图片显示状态修改回来
const onAudioEnded = () => {
openVoice.value = false
};
</script>
Tips: 如果播放语音组件在 列表
页面中使用 播放语音方法 要适当修改
例子:
<div class="listConAI" @click="handleOpenSpeech(item.msg)" >
<img
src="../../../assets/images/blueopen.png"
class="blueopenIcon"
>
<img
:src="openVoice == true ? voiceUrl : voiceDefalutUrl"
class="voiceIcon"
>
<audio
ref="audio"
:src="voicePath"
controls
hidden="true"
></audio>
</div>
const handleOpenSpeech = (value) => {
openVoice.value = !openVoice.value
// 本地链接
voicePath.value = new URL(value, import.meta.url).href
nextTick(() => {
console.log(audio.value, 'audio')
audio.value[0]?.play()
})
}