uniapp开发微信小程序时实现文字转语音播报 播报时一个字展示一个字 并有暂停语音的功能

<template>
  <div>
    <button @click="toggleSpeech">{{ isPlaying ? '暂停' : '播放' }}</button>
    <div>{{ displayedText }}</div>
  </div>
</template>

<script>
var plugin = requirePlugin("WechatSI")
export default {
  data() {
    return {
      text: '需要展示的文字',
      displayedText: '',
      isPlaying: false,
      index: 0,
      intervalId: null,
      audioContext: null,
   plugin :plugin 
    };
  },
  methods: {
    // 切换语音播报状态(播放/暂停)
    toggleSpeech() {
      if (this.isPlaying) {
        this.pauseSpeech();
      } else {
        this.startSpeech();
      }
    },
    // 开始语音播报
    startSpeech() {
      if (this.isPlaying) return;

      this.isPlaying = true;
      this.displayedText = '';
      this.index = 0;
        //获取音频的url
        this.plugin.textToSpeech({
             lang: "zh_CN",
			tts: true, //启动文本转语音功能
			content: this.text,
             success:(res)=>{
             this.audioContext = uni.createInnerAudioContext();
			 this.audioContext.src = res.filename; 		  	 
			 this.audioContext.play();
             }
      

})
     

      this.intervalId = setInterval(() => {
        if (this.index >= this.text.length) {
          this.pauseSpeech();
          return;
        }
        this.displayedText += this.text[this.index];
        this.index++;
      }, 500); // 逐个展示字的间隔时间(单位: 毫秒)
    },
    // 暂停语音播报
    pauseSpeech() {
      if (!this.isPlaying) return;

      this.isPlaying = false;
      this.audioContext && this.audioContext.pause();
      clearInterval(this.intervalId);
      uni.pauseVoice(); // 暂停语音播报
    }
  },
  beforeDestroy() {
    this.pauseSpeech();
  }
}
</script>

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值