WMS_PDA/core/utils/voice.js
2026-06-21 19:01:07 +08:00

277 lines
6.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const VOICE_API_URL = 'http://tbdata.gztbyc.com/voice/';
const VOICE_API_PATH = 'http://tbdata.gztbyc.com';
class VoiceBroadcastManager {
constructor() {
this.tts = null;
this.initPromise = null;
this.initListener = null;
this.lastText = '';
this.lastSpeakAt = 0;
this.audio = null;
}
isSupported() {
return typeof plus !== 'undefined' && (!!plus.speech || !!plus.android);
}
hasNativeSpeech() {
return typeof plus !== 'undefined' && !!plus.speech && typeof plus.speech.speak === 'function';
}
async speakByNative(text, options = {}) {
if (!this.hasNativeSpeech()) {
return false;
}
return new Promise(resolve => {
try {
const speechOptions = {
volume: Number(options.volume || 1),
speechRate: Number(options.rate || 1),
pitch: Number(options.pitch || 1)
};
try {
plus.speech.stop();
} catch (error) {
console.warn('[VoiceBroadcast] 停止旧播报失败:', error);
}
plus.speech.speak(
String(text || ''),
() => {
resolve(true);
},
error => {
console.warn('[VoiceBroadcast] 原生语音播报失败:', error);
resolve(false);
},
speechOptions
);
} catch (error) {
console.error('[VoiceBroadcast] 调用原生语音能力异常:', error);
resolve(false);
}
});
}
async ensureReady() {
if (!this.isSupported()) {
return false;
}
if (this.hasNativeSpeech()) {
return true;
}
if (this.tts) {
return true;
}
if (this.initPromise) {
return this.initPromise;
}
this.initPromise = new Promise(resolve => {
try {
const mainActivity = plus.android.runtimeMainActivity();
if (!mainActivity) {
this.initPromise = null;
resolve(false);
return;
}
const TextToSpeech = plus.android.importClass('android.speech.tts.TextToSpeech');
const Locale = plus.android.importClass('java.util.Locale');
const successCode = typeof TextToSpeech.SUCCESS === 'number' ? TextToSpeech.SUCCESS : 0;
this.initListener = plus.android.implements('android.speech.tts.TextToSpeech$OnInitListener', {
onInit: status => {
try {
if (status !== successCode && status !== 0) {
console.warn('[VoiceBroadcast] TTS 初始化失败, status:', status);
resolve(false);
return;
}
if (this.tts && typeof this.tts.setLanguage === 'function') {
const locale = Locale.CHINA || Locale.CHINESE || Locale.SIMPLIFIED_CHINESE || Locale.getDefault();
this.tts.setLanguage(locale);
this.tts.setPitch(1.0);
this.tts.setSpeechRate(1.0);
}
resolve(true);
} catch (error) {
console.error('[VoiceBroadcast] TTS 初始化异常:', error);
resolve(false);
} finally {
this.initPromise = null;
}
}
});
this.tts = new TextToSpeech(mainActivity, this.initListener);
} catch (error) {
console.error('[VoiceBroadcast] 创建 TTS 实例失败:', error);
this.tts = null;
this.initListener = null;
this.initPromise = null;
resolve(false);
}
});
return this.initPromise;
}
playByHttp(msg) {
return new Promise(resolve => {
uni.request({
url: VOICE_API_URL + msg,
method: 'GET',
timeout: 3000,
header: {
'content-type': 'text/xml; charset=utf-8'
},
success: res => {
const _src = VOICE_API_PATH + res.data.audio;
console.log('[VoiceHTTP] audio src:', _src);
// 每次重新创建 audio 实例,避免复用导致播放卡死
if (this.audio) {
this.audio.destroy();
}
const audio = uni.createInnerAudioContext();
this.audio = audio;
audio.onError(e => {
console.warn('[VoiceHTTP] audio error:', e);
resolve(false);
});
audio.onEnded(() => {
resolve(true);
});
audio.src = _src;
audio.play();
// 超时兜底:5秒后仍未触发 ended 也视为完成
setTimeout(() => resolve(true), 5000);
},
fail: err => {
console.warn('[VoiceHTTP] 请求语音失败:', err);
resolve(false);
}
});
});
}
play(msg) {
return this.playByHttp(msg);
}
async speak(text = '', options = {}) {
const content = String(text || '').trim();
if (!content) {
return false;
}
const now = Date.now();
const minInterval = Number(options.minInterval || 600);
if (!options.force && this.lastText === content && now - this.lastSpeakAt < minInterval) {
return false;
}
// 1. 优先 HTTP 语音接口
const httpResult = await this.playByHttp(content);
if (httpResult) {
this.lastText = content;
this.lastSpeakAt = Date.now();
return true;
}
// 2. 尝试原生语音播报
if (this.hasNativeSpeech()) {
const nativeResult = await this.speakByNative(content, options);
if (nativeResult) {
this.lastText = content;
this.lastSpeakAt = Date.now();
return true;
}
}
// 3. 尝试 Android TTS
const ready = await this.ensureReady();
if (ready && this.tts) {
try {
const TextToSpeech = plus.android.importClass('android.speech.tts.TextToSpeech');
const queueMode = options.flush === false
? (typeof TextToSpeech.QUEUE_ADD === 'number' ? TextToSpeech.QUEUE_ADD : 1)
: (typeof TextToSpeech.QUEUE_FLUSH === 'number' ? TextToSpeech.QUEUE_FLUSH : 0);
const rate = Number(options.rate || 1);
const pitch = Number(options.pitch || 1);
if (typeof this.tts.setSpeechRate === 'function') {
this.tts.setSpeechRate(rate);
}
if (typeof this.tts.setPitch === 'function') {
this.tts.setPitch(pitch);
}
const normalizedContent = content.replace(/\s+/g, ' ');
const utteranceId = `voice_${now}`;
try {
this.tts.speak(normalizedContent, queueMode, null, utteranceId);
} catch (error) {
this.tts.speak(normalizedContent, queueMode, null);
}
this.lastText = content;
this.lastSpeakAt = Date.now();
return true;
} catch (error) {
console.warn('[VoiceBroadcast] TTS 播报失败:', error);
}
}
return false;
}
stop() {
if (this.hasNativeSpeech()) {
try {
plus.speech.stop();
return true;
} catch (error) {
console.error('[VoiceBroadcast] 停止原生播报失败:', error);
}
}
if (!this.tts || typeof this.tts.stop !== 'function') {
return false;
}
try {
this.tts.stop();
return true;
} catch (error) {
console.error('[VoiceBroadcast] 停止播报失败:', error);
return false;
}
}
destroy() {
try {
this.stop();
if (this.tts && typeof this.tts.shutdown === 'function') {
this.tts.shutdown();
}
} catch (error) {
console.error('[VoiceBroadcast] 销毁播报器失败:', error);
} finally {
this.tts = null;
this.initPromise = null;
this.initListener = null;
}
}
}
export default new VoiceBroadcastManager();