diff --git a/uni-app/src/pages/index/index.vue b/uni-app/src/pages/index/index.vue index 0fe806a..58b7852 100644 --- a/uni-app/src/pages/index/index.vue +++ b/uni-app/src/pages/index/index.vue @@ -487,28 +487,56 @@ const playTryResult = () => { const hasChinese = /[\u4e00-\u9fa5]/.test(tryText.value) const lang = hasChinese ? 'en' : 'zh' const token = uni.getStorageSync('token') - const url = `${BASE_URL}/translate/tts?text=${encodeURIComponent(tryResult.value)}&lang=${lang}` + const text = tryResult.value uni.showLoading({ title: '语音生成中...' }) - uni.downloadFile({ - url, - header: token ? { Authorization: `Bearer ${token}` } : {}, - success: (res) => { - uni.hideLoading() - if (res.statusCode === 200) { - const audioCtx = uni.createInnerAudioContext() - audioCtx.src = res.tempFilePath - audioCtx.play() - audioCtx.onEnded(() => audioCtx.destroy()) - } else { + + if (typeof window !== 'undefined' && window.Audio) { + uni.request({ + url: `${BASE_URL}/translate/tts?text=${encodeURIComponent(text)}&lang=${lang}`, + method: 'GET', + header: { Authorization: `Bearer ${token}` }, + responseType: 'arraybuffer', + success: (res) => { + uni.hideLoading() + if (res.statusCode === 200 && res.data) { + const blob = new Blob([res.data], { type: 'audio/mpeg' }) + const url = URL.createObjectURL(blob) + const audio = new Audio(url) + audio.onended = () => { URL.revokeObjectURL(url) } + audio.play().catch(() => { + uni.showToast({ title: '播放失败,请检查音量', icon: 'none' }) + }) + } else { + uni.showToast({ title: '语音生成失败', icon: 'none' }) + } + }, + fail: () => { + uni.hideLoading() uni.showToast({ title: '语音生成失败', icon: 'none' }) - } - }, - fail: () => { - uni.hideLoading() - uni.showToast({ title: '语音生成失败', icon: 'none' }) - }, - }) + }, + }) + } else { + uni.downloadFile({ + url: `${BASE_URL}/translate/tts?text=${encodeURIComponent(text)}&lang=${lang}`, + header: { Authorization: `Bearer ${token}` }, + success: (res) => { + uni.hideLoading() + if (res.statusCode === 200) { + const audioCtx = uni.createInnerAudioContext() + audioCtx.src = res.tempFilePath + audioCtx.play() + audioCtx.onEnded(() => audioCtx.destroy()) + } else { + uni.showToast({ title: '语音生成失败', icon: 'none' }) + } + }, + fail: () => { + uni.hideLoading() + uni.showToast({ title: '语音生成失败', icon: 'none' }) + }, + }) + } }