228 lines
6.2 KiB
JavaScript
228 lines
6.2 KiB
JavaScript
import {
|
||
ref,
|
||
onUnmounted
|
||
} from 'vue'
|
||
import {
|
||
onHide,
|
||
onUnload
|
||
} from '@dcloudio/uni-app'
|
||
import config from '@/config'
|
||
import PiperTTS from './piper-bundle.js'
|
||
|
||
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
|
||
}
|
||
})
|
||
}
|
||
return piper
|
||
}
|
||
|
||
/**
|
||
* 核心朗读方法
|
||
*/
|
||
const speak = async (text) => {
|
||
if (!text) return
|
||
|
||
const processedText = extractSpeechText(text)
|
||
if (!processedText) return
|
||
|
||
const instance = getPiperInstance()
|
||
|
||
// 重置状态
|
||
isLoading.value = true
|
||
isPaused.value = false
|
||
isSpeaking.value = true
|
||
|
||
try {
|
||
// 直接调用 speak,SDK 内部会自动处理 init 和 stop
|
||
await instance.speak(processedText, {
|
||
speakerId: 0,
|
||
noiseScale: 0.667,
|
||
lengthScale: 1.0
|
||
})
|
||
} catch (e) {
|
||
console.error('TTS Speak Error:', e)
|
||
resetState()
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 暂停
|
||
*/
|
||
const pause = async () => {
|
||
// 1. 只有正在播放且未暂停时,才执行暂停
|
||
if (!isSpeaking.value || isPaused.value) return
|
||
|
||
// 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
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 恢复 (继续播放)
|
||
*/
|
||
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)
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 切换 播放/暂停 (方便按钮绑定)
|
||
*/
|
||
const togglePlay = () => {
|
||
if (isPaused.value) {
|
||
resume()
|
||
} else {
|
||
pause()
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 停止 (中断)
|
||
*/
|
||
const stop = () => {
|
||
if (piper) {
|
||
piper.stop()
|
||
}
|
||
resetState()
|
||
}
|
||
|
||
/**
|
||
* 彻底销毁
|
||
*/
|
||
const destroy = () => {
|
||
if (piper) {
|
||
piper.stop()
|
||
piper = null
|
||
}
|
||
resetState()
|
||
}
|
||
|
||
const resetState = () => {
|
||
isSpeaking.value = false
|
||
isPaused.value = false
|
||
isLoading.value = false
|
||
}
|
||
|
||
// === 生命周期管理 ===
|
||
|
||
onUnmounted(destroy)
|
||
|
||
if (typeof onHide === 'function') {
|
||
onHide(() => {
|
||
togglePlay()
|
||
// stop()
|
||
})
|
||
}
|
||
|
||
if (typeof onUnload === 'function') {
|
||
onUnload(destroy)
|
||
}
|
||
|
||
return {
|
||
speak,
|
||
pause,
|
||
resume,
|
||
togglePlay, // 新增:单按钮切换功能
|
||
stop,
|
||
cancelAudio: stop,
|
||
isSpeaking,
|
||
isPaused,
|
||
isLoading
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 文本提取工具函数 (保持原样)
|
||
*/
|
||
function extractSpeechText(markdown) {
|
||
if (!markdown || markdown.indexOf('job-json') === -1) {
|
||
return markdown;
|
||
}
|
||
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() : '';
|
||
const endingText = lastJobEndIndex < markdown.length ?
|
||
markdown.slice(lastJobEndIndex).trim() : '';
|
||
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');
|
||
} |