Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(useSpeechSynthesis): cancel speech if voice ref changes #1941

Merged
merged 1 commit into from Jul 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 3 additions & 7 deletions packages/core/useSpeechSynthesis/demo.vue
@@ -1,22 +1,18 @@
<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import { onMounted, ref } from 'vue'
import { useSpeechSynthesis } from '@vueuse/core'

const voice = ref<SpeechSynthesisVoice>({ lang: 'en-US' } as SpeechSynthesisVoice)
const voice = ref<SpeechSynthesisVoice>(undefined as unknown as SpeechSynthesisVoice)
const text = ref('Hello, everyone! Good morning!')

const speech = useSpeechSynthesis(text, {
lang: voice.value.lang,
voice,
})

let synth: SpeechSynthesis

const voices = ref<SpeechSynthesisVoice[]>([])

watch(voice, (newVoice) => {
speech.utterance.value.voice = newVoice
})

onMounted(() => {
if (speech.isSupported.value) {
// load at last
Expand Down
11 changes: 6 additions & 5 deletions packages/core/useSpeechSynthesis/index.ts
Expand Up @@ -98,11 +98,6 @@ export function useSpeechSynthesis(text: MaybeComputedRef<string>, options: UseS
utterance.onerror = (event) => {
error.value = event
}

utterance.onend = () => {
isPlaying.value = false
utterance.lang = unref(lang)
}
}

const utterance = computed(() => {
Expand All @@ -126,6 +121,12 @@ export function useSpeechSynthesis(text: MaybeComputedRef<string>, options: UseS
utterance.value.lang = lang
})

if (options.voice) {
watch(options.voice, () => {
synth!.cancel()
})
}

watch(isPlaying, () => {
if (isPlaying.value)
synth!.resume()
Expand Down