在 Nuxt 3.13 實作「語音合成」元件

實作

首先,在 stores 資料夾,建立 speechSynthesisStore.js 檔。共享語音合成的狀態,讓朗讀的聲音一次只能出現在一個地方。

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
import { defineStore } from 'pinia';

const voiceNames = {
'en': 'Aaron',
'zh-TW': 'Google 國語(臺灣)',
};

export const useSpeechSynthesisStore = defineStore('speechSynthesis', () => {
const lang = ref('zh-TW');
const voices = ref([]);
const voice = ref();
const content = ref();

const {
isPlaying,
isSupported,
speak,
stop,
} = useSpeechSynthesis(content, {
lang,
voice,
});

// 等待語音列表載入
setTimeout(() => {
voices.value = window.speechSynthesis.getVoices();
voice.value = voices.value.find(voice => voice.name === voiceNames[lang.value]);
}, 100);

const setContent = (value) => {
content.value = value;
};

const start = (content) => {
setContent(content);
speak();
};

watch(lang, (after) => {
voice.value = voices.value.find(voice => voice.name === voiceNames[after]);
});

return {
lang,
content,
isPlaying,
isSupported,
setContent,
speak: start,
stop,
};
});

components 資料夾,建立 AppSpeechRecognition.vue 檔。

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
<script setup>
const props = defineProps({
content: {
type: String,
required: true,
},
});

const speechSynthesisStore = useSpeechSynthesisStore();

const state = reactive({
isPlaying: false,
});

watch(() => speechSynthesisStore.isPlaying, (after) => {
if (after && speechSynthesisStore.content !== props.content) {
state.isPlaying = false;
}
});

onUnmounted(() => {
speechSynthesisStore.stop();
});
</script>

<template>
<slot
:is-playing="state.isPlaying"
:is-supported="speechSynthesisStore.isSupported"
:speak="() => {
state.isPlaying = true;
speechSynthesisStore.speak(props.content);
}"
:stop="() => {
state.isPlaying = false;
speechSynthesisStore.stop();
}"
/>
</template>

使用元件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<AppSpeechSynthesis
v-slot="{ isPlaying, isSupported, speak, stop }"
content="Hello, World!"
>
<v-icon
v-if="isSupported"
:icon="isPlaying ? 'mdi-stop-circle' : 'mdi-volume-high'"
icon-size="x-large"
size="x-small"
@click="() => {
isPlaying ? stop() : speak();
}"
/>
</AppSpeechSynthesis>

參考資料