rk
7 天以前 56bc142d33106db9f226abe39f60d0059d702338
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<template>
    <view style="padding: 40rpx;">
        <button @click="speak('订单已收到,开始播报')">开始播报</button>
    </view>
</template>
 
<script>
    export default {
        data() {
            return {
                tts: null // 原生TTS对象
            }
        },
 
        onReady() {
            this.initTTS() // 页面渲染完成初始化语音
        },
 
        methods: {
            // ========== 初始化安卓原生语音 ==========
            initTTS() {
                if (uni.getSystemInfoSync().platform !== 'android') {
                    console.log('仅支持安卓')
                    return
                }
 
                try {
                    // 导入安卓原生类
                    const TextToSpeech = plus.android.importClass('android.speech.tts.TextToSpeech')
                    const Locale = plus.android.importClass('java.util.Locale')
 
                    // 创建TTS
                    this.tts = new TextToSpeech(plus.android.runtimeMainActivity(), {
                        onInit: (status) => {
                            if (status == 0) {
                                // 设置中文
                                this.tts.setLanguage(Locale.CHINA)
                                console.log('语音初始化成功')
                            }
                        }
                    })
                } catch (e) {
                    console.log('初始化失败', e)
                }
            },
 
            // ========== 语音播报(核心方法) ==========
            speak(text) {
                if (!this.tts) {
                    uni.showToast({
                        title: '语音未准备好',
                        icon: 'none'
                    })
                    return
                }
 
                try {
                    // 安卓原生播报(QUEUE_FLUSH = 立即播报,打断上一条)
                    this.tts.speak(text, 0, null)
                } catch (err) {
                    console.log('播报失败', err)
                }
            },
 
            // 停止播报
            stopSpeak() {
                if (this.tts) this.tts.stop()
            }
        },
 
        // 页面销毁时关闭语音
        onUnload() {
            if (this.tts) {
                this.tts.stop()
                this.tts.shutdown()
            }
        }
    }
</script>