feat: add qwen tts voice preferences

This commit is contained in:
2026-07-23 22:37:12 +08:00
parent 39ff6f6ceb
commit 4902830e6d
7 changed files with 273 additions and 11 deletions
@@ -271,6 +271,16 @@
</view>
<text class="display-note">切换后同步到今日、练、问、我全部页面,并自动保存。</text>
</template>
<view v-if="loggedIn" class="voice-preference-row">
<view class="display-heading-copy">
<text class="menu-item-title">AI 播报音色</text>
<text class="menu-item-desc">{{ currentTtsVoiceLabel }} · 对练情绪和语速仍会保留</text>
</view>
<picker :range="qwenTtsVoiceOptions" range-key="label" :value="ttsVoiceOptionIndex" @change="changeTtsVoice">
<view class="voice-picker-value">{{ currentTtsVoiceLabel }} <uni-icons type="right" size="12" color="#94a3b8" /></view>
</picker>
</view>
</view>
</view>
</template>
@@ -297,6 +307,12 @@ import {
import { getCompetencyProfile, getPracticeHistory, getPromotionEvidence } from '@/services/practice';
import { resetPageScroll } from '@/services/navigation';
import { ensureEmployeePosition } from '@/services/position';
import {
getTtsVoicePreference,
qwenTtsVoiceOptions,
setTtsVoicePreference,
type TtsVoicePreference
} from '@/services/tts-voice-preference';
const loggedIn = ref(false);
const phone = ref('');
@@ -313,9 +329,14 @@ const evidence = ref<PromotionEvidence | null>(null);
const positionProfile = ref(getSelectedPositionProfile());
const supervisorLearning = ref(false);
const fontSize = ref<AppFontSize>(getAppFontSize());
const ttsVoice = ref<TtsVoicePreference>('');
const currentFontSizeLabel = computed(() =>
appFontSizeOptions.find((item) => item.value === fontSize.value)?.label || '标准'
);
const ttsVoiceOptionIndex = computed(() => Math.max(0, qwenTtsVoiceOptions.findIndex((item) => item.value === ttsVoice.value)));
const currentTtsVoiceLabel = computed(() =>
qwenTtsVoiceOptions[ttsVoiceOptionIndex.value]?.label || '跟随场景'
);
const maskedPhone = computed(() => {
const value = phone.value.trim();
if (!value) return '未登录';
@@ -333,6 +354,7 @@ const refreshAuth = () => {
positionProfile.value = getSelectedPositionProfile();
supervisorLearning.value = isSupervisorLearnerMode();
fontSize.value = getAppFontSize();
ttsVoice.value = getTtsVoicePreference(auth.tenantId, auth.phone);
};
const changeFontSize = (value: AppFontSize) => {
@@ -340,6 +362,13 @@ const changeFontSize = (value: AppFontSize) => {
uni.showToast({ title: `已切换为${currentFontSizeLabel.value}`, icon: 'none' });
};
const changeTtsVoice = (event: { detail?: { value?: string | number } }) => {
const option = qwenTtsVoiceOptions[Number(event.detail?.value)];
const auth = getAuth();
ttsVoice.value = setTtsVoicePreference(auth.tenantId, auth.phone, option?.value);
uni.showToast({ title: `已切换为${currentTtsVoiceLabel.value}`, icon: 'none' });
};
const returnToSupervisor = () => {
leaveSupervisorLearnerMode();
supervisorLearning.value = false;
@@ -650,6 +679,28 @@ onShow(() => {
box-shadow: 0 4px 12px rgba(24, 34, 48, 0.08);
}
.voice-preference-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding-top: 12px;
border-top: 1px solid var(--employee-line);
}
.voice-picker-value {
display: flex;
align-items: center;
gap: 3px;
max-width: 150px;
padding: 8px 10px;
border: 1px solid #e3e6ea;
border-radius: 10px;
color: var(--employee-text);
font-size: 12px;
white-space: nowrap;
}
.profile-summary {
border-color: var(--employee-line);
}
+15 -8
View File
@@ -1,6 +1,8 @@
import type { AsrResponse, PracticeTtsContext, SpeechPlaybackStatus, SpeechSelectedFile, SpeechVoiceProfile, TtsResponse } from '@/types/api';
import { apiRequest, apiUrl, authHeaders, readTextPayload } from './api';
import { getAuth } from './auth';
import type { SpeechCapture } from './speech-capture';
import { applyTtsVoicePreference, getTtsVoicePreference } from './tts-voice-preference';
const audioExtensions = ['.mp3', '.wav', '.m4a', '.webm', '.aac', '.ogg'];
@@ -103,11 +105,16 @@ export const transcribeSpeechCapture = (
? transcribeSpeechBlob(capture.blob, filename, registerAbort)
: transcribeSpeechFile(capture.file, registerAbort);
export const resolveTtsVoiceProfile = (voiceProfile?: SpeechVoiceProfile) => {
const auth = getAuth();
return applyTtsVoicePreference(voiceProfile, getTtsVoicePreference(auth.tenantId, auth.phone));
};
export const synthesizeSpeech = (text: string, voiceProfile?: SpeechVoiceProfile, practiceContext?: PracticeTtsContext) =>
apiRequest<TtsResponse>({
url: '/api/ai/tts',
method: 'POST',
data: { text: text.trim().slice(0, 300), voiceProfile, practiceContext },
data: { text: text.trim().slice(0, 300), voiceProfile: resolveTtsVoiceProfile(voiceProfile), practiceContext },
timeout: 60000
});
@@ -221,8 +228,8 @@ export const createSpeechPlaybackController = (
stop();
const value = text.trim();
if (!value) return;
const profile = voiceProfile || defaultVoiceProfile;
const sourceKey = cacheKey(value, profile, practiceContext);
const effectiveProfile = resolveTtsVoiceProfile(voiceProfile || defaultVoiceProfile);
const sourceKey = cacheKey(value, effectiveProfile, practiceContext);
const currentGeneration = generation;
publish(key, 'loading');
try {
@@ -233,7 +240,7 @@ export const createSpeechPlaybackController = (
playAudioSource(key, cachedSource, sourceKey, currentGeneration);
return;
}
const result = await synthesizeSpeech(value, profile, practiceContext);
const result = await synthesizeSpeech(value, effectiveProfile, practiceContext);
if (currentGeneration !== generation || activeKey !== key) return;
const source = result.inlineAudioUrl || result.audioUrl;
if (!source) throw new Error('语音合成未返回音频');
@@ -246,7 +253,7 @@ export const createSpeechPlaybackController = (
playAudioSource(key, source, sourceKey, currentGeneration);
} catch (error) {
if (currentGeneration !== generation) return;
const browserFallback = playWithBrowserSpeech(key, value, currentGeneration, profile);
const browserFallback = playWithBrowserSpeech(key, value, currentGeneration, effectiveProfile);
if (browserFallback.played) return;
stop();
onError(browserFallback.message || (error instanceof Error ? error.message : '语音生成失败'));
@@ -261,12 +268,12 @@ export const createSpeechPlaybackController = (
const preload = async (text: string, voiceProfile?: SpeechVoiceProfile, practiceContext?: PracticeTtsContext): Promise<string | null> => {
const value = text.trim();
if (!value) return null;
const profile = voiceProfile || defaultVoiceProfile;
const sourceKey = cacheKey(value, profile, practiceContext);
const effectiveProfile = resolveTtsVoiceProfile(voiceProfile || defaultVoiceProfile);
const sourceKey = cacheKey(value, effectiveProfile, practiceContext);
const cached = sourceCache.get(sourceKey);
if (cached) return cached;
try {
const result = await synthesizeSpeech(value, profile, practiceContext);
const result = await synthesizeSpeech(value, effectiveProfile, practiceContext);
const source = result.inlineAudioUrl || result.audioUrl;
if (!source) return null;
sourceCache.set(sourceKey, source);
@@ -0,0 +1,43 @@
import type { SpeechVoiceProfile } from '@/types/api';
export const qwenTtsVoiceOptions = [
{ value: '', label: '跟随场景' },
{ value: 'longanhuan_v3.6', label: '龙安欢 · 中文女声' },
{ value: 'longjielidou_v3.6', label: '龙杰里斗 · 童声' },
{ value: 'loongeva_v3.6', label: 'Loongeva · 英文女声' },
{ value: 'loongjohn', label: 'Loongjohn · 英文男声' }
] as const;
export type TtsVoicePreference = typeof qwenTtsVoiceOptions[number]['value'];
const preferenceKeyPrefix = 'aihr_tts_voice';
export const normalizeTtsVoicePreference = (value: unknown): TtsVoicePreference =>
qwenTtsVoiceOptions.some((option) => option.value === value) ? value as TtsVoicePreference : '';
export const ttsVoicePreferenceStorageKey = (tenantId: unknown, phone: unknown) => {
const tenant = String(tenantId || '').trim();
const account = String(phone || '').trim();
return tenant && account ? `${preferenceKeyPrefix}:${tenant}:${account}` : '';
};
export const getTtsVoicePreference = (tenantId: unknown, phone: unknown): TtsVoicePreference => {
const key = ttsVoicePreferenceStorageKey(tenantId, phone);
return key ? normalizeTtsVoicePreference(uni.getStorageSync(key)) : '';
};
export const setTtsVoicePreference = (tenantId: unknown, phone: unknown, value: unknown): TtsVoicePreference => {
const key = ttsVoicePreferenceStorageKey(tenantId, phone);
const normalized = normalizeTtsVoicePreference(value);
if (key) uni.setStorageSync(key, normalized);
return normalized;
};
export const applyTtsVoicePreference = (
profile: SpeechVoiceProfile | undefined,
preference: unknown
): SpeechVoiceProfile | undefined => {
const voice = normalizeTtsVoicePreference(preference);
if (!voice) return profile;
return { ...(profile || { role: 'neutral' }), voice };
};
@@ -39,10 +39,10 @@ test('全局选择只覆盖 voice,保留场景角色、情绪、语速和方
const profile = { role: 'customer', emotion: 'intense', speed: 1.12, dialect: 'sichuanese' };
assert.deepEqual(
runtime.applyTtsVoicePreference(profile, 'longanhuan_v3.6'),
JSON.parse(JSON.stringify(runtime.applyTtsVoicePreference(profile, 'longanhuan_v3.6'))),
{ ...profile, voice: 'longanhuan_v3.6' }
);
assert.deepEqual(runtime.applyTtsVoicePreference(profile, ''), profile);
assert.deepEqual(JSON.parse(JSON.stringify(runtime.applyTtsVoicePreference(profile, ''))), profile);
});
test('语音播放链路在合成前统一注入全局音色,且缓存键包含处理后的 profile', async () => {