Files
qingdao-employment-service/hook/useTTSPlayer.js

228 lines
6.2 KiB
JavaScript
Raw Normal View History

2025-04-16 14:24:06 +08:00
import {
ref,
onUnmounted
2025-04-16 14:24:06 +08:00
} from 'vue'
import {
onHide,
onUnload
} from '@dcloudio/uni-app'
2025-12-06 14:18:33 +08:00
import config from '@/config'
import PiperTTS from './piper-bundle.js'
2025-04-16 14:24:06 +08:00
2025-12-06 14:18:33 +08:00
export function useTTSPlayer() {
// UI 状态
const isSpeaking = ref(false) // 是否正在交互(含播放、暂停、加载)
const isPaused = ref(false) // 是否处于暂停状态
const isLoading = ref(false) // 是否正在加载/连接
// 单例 Piper 实例
let piper = null
/**
* 获取或创建 SDK 实例
*/
const getPiperInstance = () => {
if (!piper) {
let baseUrl = config.speechSynthesis2 || ''
baseUrl = baseUrl.replace(/\/$/, '')
piper = new PiperTTS({
baseUrl: baseUrl,
sampleRate: 16000,
onStatus: (msg, type) => {
if (type === 'error') {
console.error('[TTS Error]', msg)
resetState()
}
},
onStart: () => {
isLoading.value = false
isSpeaking.value = true
isPaused.value = false
},
onEnd: () => {
// 只有非暂停状态下的结束,才重置所有状态
// 如果是用户手动暂停导致的中断,不应视为自然播放结束
isSpeaking.value = false
isLoading.value = false
isPaused.value = false
}
})
2025-04-16 14:24:06 +08:00
}
return piper
2025-04-16 14:24:06 +08:00
}
/**
* 核心朗读方法
*/
const speak = async (text) => {
if (!text) return
2025-04-16 14:24:06 +08:00
const processedText = extractSpeechText(text)
if (!processedText) return
2025-04-16 14:24:06 +08:00
const instance = getPiperInstance()
2025-04-16 14:24:06 +08:00
// 重置状态
isLoading.value = true
isPaused.value = false
isSpeaking.value = true
2025-04-16 14:24:06 +08:00
try {
// 直接调用 speakSDK 内部会自动处理 init 和 stop
await instance.speak(processedText, {
speakerId: 0,
noiseScale: 0.667,
lengthScale: 1.0
})
} catch (e) {
console.error('TTS Speak Error:', e)
resetState()
2025-04-16 14:24:06 +08:00
}
}
/**
* 暂停
*/
const pause = async () => {
// 1. 只有正在播放且未暂停时,才执行暂停
if (!isSpeaking.value || isPaused.value) return
2025-04-16 14:24:06 +08:00
// 2. 检查播放器实例是否存在
if (piper && piper.player) {
try {
// 执行音频挂起
await piper.player.pause()
// 3. 成功后更新 UI
isPaused.value = true
} catch (e) {
console.error("Pause failed:", e)
// 即使报错,如果不是致命错误,也可以尝试强制更新 UI
// isPaused.value = true
2025-04-16 14:24:06 +08:00
}
}
}
2025-04-16 14:24:06 +08:00
/**
* 恢复 (继续播放)
*/
const resume = async () => {
// 1. 只有处于暂停状态时,才执行恢复
if (!isPaused.value) return
if (piper && piper.player) {
try {
await piper.player.continue()
// 2. 成功后更新 UI
isPaused.value = false
isSpeaking.value = true
} catch (e) {
console.error("Resume failed:", e)
2025-04-16 14:24:06 +08:00
}
}
}
/**
* 切换 播放/暂停 (方便按钮绑定)
*/
const togglePlay = () => {
if (isPaused.value) {
resume()
} else {
pause()
2025-04-16 14:24:06 +08:00
}
}
/**
* 停止 (中断)
*/
const stop = () => {
if (piper) {
piper.stop()
2025-04-16 14:24:06 +08:00
}
resetState()
2025-04-16 14:24:06 +08:00
}
/**
* 彻底销毁
*/
const destroy = () => {
if (piper) {
piper.stop()
piper = null
2025-04-16 14:24:06 +08:00
}
resetState()
}
2025-04-16 14:24:06 +08:00
const resetState = () => {
isSpeaking.value = false
isPaused.value = false
isLoading.value = false
}
2025-04-16 14:24:06 +08:00
// === 生命周期管理 ===
2025-04-16 14:24:06 +08:00
onUnmounted(destroy)
if (typeof onHide === 'function') {
onHide(() => {
togglePlay()
// stop()
})
}
if (typeof onUnload === 'function') {
onUnload(destroy)
}
2025-04-16 14:24:06 +08:00
return {
speak,
pause,
resume,
togglePlay, // 新增:单按钮切换功能
stop,
cancelAudio: stop,
2025-04-16 14:24:06 +08:00
isSpeaking,
isPaused,
isLoading
2025-04-16 14:24:06 +08:00
}
}
/**
* 文本提取工具函数 (保持原样)
*/
2025-04-16 14:24:06 +08:00
function extractSpeechText(markdown) {
if (!markdown || markdown.indexOf('job-json') === -1) {
return markdown;
}
2025-04-16 14:24:06 +08:00
const jobRegex = /``` job-json\s*({[\s\S]*?})\s*```/g;
const jobs = [];
let match;
let lastJobEndIndex = 0;
let firstJobStartIndex = -1;
while ((match = jobRegex.exec(markdown)) !== null) {
const jobStr = match[1];
try {
const job = JSON.parse(jobStr);
jobs.push(job);
if (firstJobStartIndex === -1) {
firstJobStartIndex = match.index;
}
lastJobEndIndex = jobRegex.lastIndex;
} catch (e) {
console.warn('JSON 解析失败', e);
}
}
const guideText = firstJobStartIndex > 0 ?
markdown.slice(0, firstJobStartIndex).trim() : '';
2025-04-16 14:24:06 +08:00
const endingText = lastJobEndIndex < markdown.length ?
markdown.slice(lastJobEndIndex).trim() : '';
2025-04-16 14:24:06 +08:00
const jobTexts = jobs.map((job, index) => {
return `${index + 1} 个岗位,岗位名称是:${job.jobTitle},公司是:${job.companyName},薪资:${job.salary},地点:${job.location},学历要求:${job.education},经验要求:${job.experience}`;
});
const finalTextParts = [];
if (guideText) finalTextParts.push(guideText);
finalTextParts.push(...jobTexts);
if (endingText) finalTextParts.push(endingText);
return finalTextParts.join('\n');
}