fix: 首页TTS同样改用blob播放,解决downloadFile导致页面刷新的问题

This commit is contained in:
TradeMate Dev
2026-05-17 14:18:29 +08:00
parent 7b7f90d57a
commit 1fabad0fe9
+47 -19
View File
@@ -487,28 +487,56 @@ const playTryResult = () => {
const hasChinese = /[\u4e00-\u9fa5]/.test(tryText.value) const hasChinese = /[\u4e00-\u9fa5]/.test(tryText.value)
const lang = hasChinese ? 'en' : 'zh' const lang = hasChinese ? 'en' : 'zh'
const token = uni.getStorageSync('token') 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.showLoading({ title: '语音生成中...' })
uni.downloadFile({
url, if (typeof window !== 'undefined' && window.Audio) {
header: token ? { Authorization: `Bearer ${token}` } : {}, uni.request({
success: (res) => { url: `${BASE_URL}/translate/tts?text=${encodeURIComponent(text)}&lang=${lang}`,
uni.hideLoading() method: 'GET',
if (res.statusCode === 200) { header: { Authorization: `Bearer ${token}` },
const audioCtx = uni.createInnerAudioContext() responseType: 'arraybuffer',
audioCtx.src = res.tempFilePath success: (res) => {
audioCtx.play() uni.hideLoading()
audioCtx.onEnded(() => audioCtx.destroy()) if (res.statusCode === 200 && res.data) {
} else { 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' }) uni.showToast({ title: '语音生成失败', icon: 'none' })
} },
}, })
fail: () => { } else {
uni.hideLoading() uni.downloadFile({
uni.showToast({ title: '语音生成失败', icon: 'none' }) 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' })
},
})
}
} }
</script> </script>