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 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' })
},
})
}
}
</script>