diff --git a/.env.example b/.env.example index bfacddad..eb86130a 100644 --- a/.env.example +++ b/.env.example @@ -24,7 +24,7 @@ AUTH_TRUST_HOST=true # 普通用户每天可发起的 AI 操作次数(默认 0,不限制;管理员不受限制)。网页中「设置 → 用户管理」保存的值优先 # AI_DAILY_LIMIT=0 -# 动画语音讲解的朗读方式(默认 browser):browser 为浏览器本地语音;minimax、qwen、glm、stepfun、volcengine、volcengine-agent 为云端语音,复用下方对应渠道的 API Key。 +# 动画语音讲解的朗读方式(默认 browser):browser 为浏览器本地语音;minimax、qwen、glm、stepfun、volcengine、volcengine-agent、openai 为云端语音,复用下方对应渠道的 API Key。 # 网页中「设置 → AI 设置 → 语音讲解」保存的值优先 # TTS_MODE=browser # 火山引擎豆包语音的 API Key(与火山方舟的 Key 不同,在豆包语音控制台创建) diff --git a/README.en.md b/README.en.md index d84bf2c1..6a3ab040 100644 --- a/README.en.md +++ b/README.en.md @@ -33,7 +33,7 @@ An AI-powered notebook for the questions you got wrong. Snap a photo or type a q | Voice | Sound | Cost | | :--- | :--- | :--- | | Browser voice (Web Speech) | Read by the device's built-in voice; sounds stiff, and the voice varies by device | Free | -| Cloud TTS (MiniMax, Qwen, Zhipu GLM-TTS, StepFun, Volcengine Doubao Speech, Volcengine Agent Plan) | Natural, just like a real person explaining the problem, and the same on every device | Paid; **a Token Plan or similar subscription is recommended** over pay-as-you-go | +| Cloud TTS (MiniMax, Qwen, Zhipu GLM-TTS, StepFun, Volcengine Doubao Speech, Volcengine Agent Plan, OpenAI) | Natural, just like a real person explaining the problem, and the same on every device | Paid; **a Token Plan or similar subscription is recommended** over pay-as-you-go | Admins switch between them under **Settings → AI → Voice narration**. See [Cloud voice narration](doc/wiki/en/AI-Configuration-en.md#cloud-voice-narration). @@ -161,7 +161,7 @@ Practice statistics show total practice, accuracy and active months, with distri ### Explanations and demos -- **🎬 SVG animated explanations**: AI generates step-by-step SVG animations of the solution, with play/pause, seeking, replay and full screen. Click the speaker icon in the player for voice narration: each step is read aloud, the animation waits for the narration before moving on, and the speed is adjustable. There are two kinds of voice: the **browser voice** is free but sounds stiff and varies by device; **cloud TTS** (MiniMax, Qwen, Zhipu GLM-TTS, StepFun, Volcengine Doubao Speech, Volcengine Agent Plan) sounds natural, just like a real person, but is paid, and a Token Plan, Step Plan or similar subscription is recommended over pay-as-you-go. Admins switch under **Settings → AI → Voice narration**; the server synthesizes a young male voice normalized to about -15 LUFS. Voice generation is registered as a background task, animations with generated voice open with narration on, existing animations can **Regenerate voice**, and synthesized voice is included in data export and import. Older animations without a narration script read the on-screen subtitles, or click **Add narration** to have AI write only the script while keeping the picture unchanged. Animation text follows the interface language: the English interface generates an English version and the Chinese interface a Chinese one. Both are kept, and switching the language shows the matching version automatically. On by default; turn it off in **Settings → General**. +- **🎬 SVG animated explanations**: AI generates step-by-step SVG animations of the solution, with play/pause, seeking, replay and full screen. Click the speaker icon in the player for voice narration: each step is read aloud, the animation waits for the narration before moving on, and the speed is adjustable. There are two kinds of voice: the **browser voice** is free but sounds stiff and varies by device; **cloud TTS** (MiniMax, Qwen, Zhipu GLM-TTS, StepFun, Volcengine Doubao Speech, Volcengine Agent Plan, OpenAI) sounds natural, just like a real person, but is paid, and a Token Plan, Step Plan or similar subscription is recommended over pay-as-you-go. Admins switch under **Settings → AI → Voice narration**; the server synthesizes a young male voice normalized to about -15 LUFS. Voice generation is registered as a background task, animations with generated voice open with narration on, existing animations can **Regenerate voice**, and synthesized voice is included in data export and import. Older animations without a narration script read the on-screen subtitles, or click **Add narration** to have AI write only the script while keeping the picture unchanged. Animation text follows the interface language: the English interface generates an English version and the Chinese interface a Chinese one. Both are kept, and switching the language shows the matching version automatically. On by default; turn it off in **Settings → General**. - **📐 GeoGebra demos**: for math and physics questions, AI can generate interactive GeoGebra figures. Off by default; turn it on in **Settings → General**. - Generated animations and GeoGebra demos can be deleted (with confirmation). @@ -355,7 +355,7 @@ Data directories, default accounts and local builds are described in [INSTALL_PA | `HTTP_PROXY` / `HTTPS_PROXY` | Proxy | None | Proxy for requests to AI services | | `ALLOW_REGISTRATION` | Allow sign-ups | `false` | When `true`, registration is open by default; the switch saved by an admin under **Settings → User Management** takes precedence | | `AI_DAILY_LIMIT` | Daily AI limit per user | `0` (unlimited) | AI actions each regular user can start per day; admins are not limited. The value saved under **Settings → User Management** takes precedence | -| `TTS_MODE` | How animation narration is voiced | `browser` | `browser` uses the browser's voice; `minimax`, `qwen`, `glm`, `stepfun`, `volcengine` or `volcengine-agent` uses a cloud voice with that channel's API key (Doubao Speech uses `VOLCENGINE_TTS_API_KEY`). The value saved under **Settings → AI → Voice narration** takes precedence | +| `TTS_MODE` | How animation narration is voiced | `browser` | `browser` uses the browser's voice; `minimax`, `qwen`, `glm`, `stepfun`, `volcengine`, `volcengine-agent` or `openai` uses a cloud voice with that channel's API key (Doubao Speech uses `VOLCENGINE_TTS_API_KEY`; OpenAI uses the active OpenAI configuration). The value saved under **Settings → AI → Voice narration** takes precedence | **AI** (settings saved in the web UI take precedence over environment variables) diff --git a/README.md b/README.md index 92ef18f2..6b87873b 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ | 语音 | 效果 | 费用 | | :--- | :--- | :--- | | 浏览器本地语音(Web Speech) | 由设备自带的语音朗读,听起来比较生硬,音色因设备而异 | 免费 | -| 云端 TTS 语音(MiniMax、千问、智谱 GLM-TTS、阶跃星辰、火山引擎豆包语音、火山引擎 Agent Plan) | 声音自然,与真人讲题无异,所有设备音色一致 | 需要付费,**建议购买 Token Plan 等套餐**,比按量付费划算 | +| 云端 TTS 语音(MiniMax、千问、智谱 GLM-TTS、阶跃星辰、火山引擎豆包语音、火山引擎 Agent Plan、OpenAI) | 声音自然,与真人讲题无异,所有设备音色一致 | 需要付费,**建议购买 Token Plan 等套餐**,比按量付费划算 | 管理员在「设置 → AI 设置 → 语音讲解」中切换,详见 [云端语音讲解](doc/wiki/AI-Configuration.md#云端语音讲解)。 @@ -159,7 +159,7 @@ ### 讲解与演示 -- **🎬 SVG 动画讲解**:AI 按解题思路生成分步骤的 SVG 动画,支持播放/暂停、拖动进度、重播和全屏。点击播放器上的喇叭可开启语音讲解,朗读每一步的讲解,画面会等语音读完再进入下一步,语速可调。语音有两种:**浏览器本地语音**免费,但听起来较生硬、音色因设备而异;**云端 TTS 语音**(MiniMax、千问、智谱 GLM-TTS、阶跃星辰、火山引擎豆包语音、火山引擎 Agent Plan)声音自然、与真人无异,需要付费,建议购买各家的 Token Plan、Step Plan 等套餐而不是按量付费。管理员在「设置 → AI 设置 → 语音讲解」中切换,服务端合成年轻男声并统一到约 -15 LUFS 的响度;生成语音登记为后台任务,已生成语音的动画打开时默认开启语音讲解,已有动画可「重新生成语音」,合成的语音随数据导出、导入备份;旧动画没有讲解稿时朗读画面字幕,也可点击「补充讲解稿」由 AI 只补写讲解稿,画面保持不变。动画文字与界面语言一致:中文界面生成中文版、英文界面生成英文版,两种版本分别保存,切换语言时自动显示对应版本。默认开启,可在「设置 → 通用」中关闭。 +- **🎬 SVG 动画讲解**:AI 按解题思路生成分步骤的 SVG 动画,支持播放/暂停、拖动进度、重播和全屏。点击播放器上的喇叭可开启语音讲解,朗读每一步的讲解,画面会等语音读完再进入下一步,语速可调。语音有两种:**浏览器本地语音**免费,但听起来较生硬、音色因设备而异;**云端 TTS 语音**(MiniMax、千问、智谱 GLM-TTS、阶跃星辰、火山引擎豆包语音、火山引擎 Agent Plan、OpenAI)声音自然、与真人无异,需要付费,建议购买各家的 Token Plan、Step Plan 等套餐而不是按量付费。管理员在「设置 → AI 设置 → 语音讲解」中切换,服务端合成年轻男声并统一到约 -15 LUFS 的响度;生成语音登记为后台任务,已生成语音的动画打开时默认开启语音讲解,已有动画可「重新生成语音」,合成的语音随数据导出、导入备份;旧动画没有讲解稿时朗读画面字幕,也可点击「补充讲解稿」由 AI 只补写讲解稿,画面保持不变。动画文字与界面语言一致:中文界面生成中文版、英文界面生成英文版,两种版本分别保存,切换语言时自动显示对应版本。默认开启,可在「设置 → 通用」中关闭。 - **📐 GeoGebra 动态演示**:数学、物理题可由 AI 生成交互式 GeoGebra 图形。默认关闭,可在「设置 → 通用」中开启。 - 已生成的动画讲解和 GeoGebra 演示都可删除(需二次确认)。 @@ -353,7 +353,7 @@ wrong-notebook --port 3000 | `HTTP_PROXY` / `HTTPS_PROXY` | 代理 | 无 | 访问 AI 服务时使用的代理 | | `ALLOW_REGISTRATION` | 允许注册 | `false` | 为 `true` 时默认开放注册;管理员在「设置 → 用户管理」中保存的开关优先 | | `AI_DAILY_LIMIT` | 每人每日 AI 次数 | `0`(不限制) | 普通用户每天可发起的 AI 操作次数,管理员不受限制;「设置 → 用户管理」中保存的值优先 | -| `TTS_MODE` | 动画语音讲解的朗读方式 | `browser` | `browser` 为浏览器本地语音;`minimax`、`qwen`、`glm`、`stepfun`、`volcengine`、`volcengine-agent` 为云端语音,复用对应渠道的 API Key(豆包语音使用 `VOLCENGINE_TTS_API_KEY`)。「设置 → AI 设置 → 语音讲解」中保存的值优先 | +| `TTS_MODE` | 动画语音讲解的朗读方式 | `browser` | `browser` 为浏览器本地语音;`minimax`、`qwen`、`glm`、`stepfun`、`volcengine`、`volcengine-agent`、`openai` 为云端语音,复用对应渠道的 API Key(豆包语音使用 `VOLCENGINE_TTS_API_KEY`,OpenAI 使用当前激活的 OpenAI 配置)。「设置 → AI 设置 → 语音讲解」中保存的值优先 | **AI 配置**(网页中保存的配置优先于环境变量) diff --git a/doc/wiki/AI-Configuration.md b/doc/wiki/AI-Configuration.md index bd68bc1a..7e196a87 100644 --- a/doc/wiki/AI-Configuration.md +++ b/doc/wiki/AI-Configuration.md @@ -60,6 +60,7 @@ MiniMax Code OAuth 用 MiniMax Code 账号登录后调用模型,不需要 API | 阶跃星辰(建议使用 Step Plan) | 与阶跃星辰渠道共用 | `stepaudio-2.5-tts`,音色 `qingniandaxuesheng`(青年大学生),并以指令约束语气 | 阶跃星辰 Base URL 加 `/audio/speech`,即 `https://api.stepfun.com/step_plan/v1/audio/speech` | | 火山引擎豆包语音(建议购买资源包) | 单独的豆包语音 API Key(在[豆包语音控制台](https://console.volcengine.com/speech)创建,与火山方舟不同) | 资源 ID `seed-tts-2.0`(填在「语音模型」),音色 `zh_male_yangguangqingnian_uranus_bigtts`(阳光青年 2.0) | `https://openspeech.bytedance.com/api/v3/tts/unidirectional` | | 火山引擎 Agent Plan(计入套餐额度) | 与火山引擎 Agent Plan 渠道共用 | 资源 ID `seed-tts-2.0`,音色 `zh_male_yangguangqingnian_uranus_bigtts` | `https://openspeech.bytedance.com/api/v3/plan/tts/unidirectional` | +| OpenAI | 可单独填写;留空时使用「AI 设置」中当前激活的 OpenAI 配置 | `gpt-4o-mini-tts`,音色 `cedar`,并以指令约束语气(OpenAI 计划于 2027-01-06 下线该模型) | OpenAI Base URL 加 `/audio/speech`,即 `https://api.openai.com/v1/audio/speech` | | 智谱 GLM-TTS(建议使用 GLM Coding Plan) | 与智谱 GLM 渠道共用 | `glm-tts`,音色 `xiaochen`(小陈) | GLM Base URL 加 `/audio/speech`,即 `https://open.bigmodel.cn/api/paas/v4/audio/speech` | - 默认音色为年轻男声,自然、清晰、略带科技感;千问另用指令要求不用播音腔、不模仿角色。模型、音色和接口地址都可修改(API Key 旁附获取说明,其余字段旁附服务商的说明文档或音色列表链接),「保存并试听」会先保存设置再朗读一段示例,失败时在按钮下方显示服务商的原始报错(如 MiniMax 的 `2056` 表示 Token Plan 当前用量窗口的额度已用完)。 diff --git a/doc/wiki/en/AI-Configuration-en.md b/doc/wiki/en/AI-Configuration-en.md index 6a1993f5..aad5adb9 100644 --- a/doc/wiki/en/AI-Configuration-en.md +++ b/doc/wiki/en/AI-Configuration-en.md @@ -60,6 +60,7 @@ Animation narration is read by the browser's own voice (Web Speech) by default. | StepFun (Step Plan recommended) | Shared with the StepFun channel | `stepaudio-2.5-tts`, voice `qingniandaxuesheng`, with a style instruction | StepFun base URL plus `/audio/speech`, i.e. `https://api.stepfun.com/step_plan/v1/audio/speech` | | Volcengine Doubao Speech (resource pack recommended) | Its own Doubao Speech API key (create it in the [Doubao Speech console](https://console.volcengine.com/speech); different from Volcengine Ark) | Resource ID `seed-tts-2.0` (in the speech model field), voice `zh_male_yangguangqingnian_uranus_bigtts` | `https://openspeech.bytedance.com/api/v3/tts/unidirectional` | | Volcengine Agent Plan (counts toward the plan) | Shared with the Volcengine Agent Plan channel | Resource ID `seed-tts-2.0`, voice `zh_male_yangguangqingnian_uranus_bigtts` | `https://openspeech.bytedance.com/api/v3/plan/tts/unidirectional` | +| OpenAI | Optional; leave empty to use the OpenAI configuration active in AI settings | `gpt-4o-mini-tts`, voice `cedar`, with a style instruction (OpenAI plans to retire the model on 2027-01-06) | OpenAI base URL plus `/audio/speech`, i.e. `https://api.openai.com/v1/audio/speech` | | Zhipu GLM-TTS (GLM Coding Plan recommended) | Shared with the GLM channel | `glm-tts`, voice `xiaochen` | GLM base URL plus `/audio/speech`, i.e. `https://open.bigmodel.cn/api/paas/v4/audio/speech` | - The default voice is a young male voice that sounds natural, clear and slightly techy; for Qwen, an instruction also asks for no broadcast tone and no character imitation. Model, voice and endpoint can be changed (the API key links to how to get one, and the other fields link to the provider's docs or voice list), and **Save and preview** saves the settings before reading a sample; if it fails, the provider's original error appears below the buttons (for example, MiniMax `2056` means the current Token Plan usage window is used up). diff --git a/src/__tests__/integration/tts-api.test.ts b/src/__tests__/integration/tts-api.test.ts index 5c37a239..7e828fe5 100644 --- a/src/__tests__/integration/tts-api.test.ts +++ b/src/__tests__/integration/tts-api.test.ts @@ -117,6 +117,20 @@ describe('云端语音接口', () => { expect(mocks.fetch).toHaveBeenCalledTimes(2); }); + it('OpenAI 语音使用当前激活的 OpenAI 实例的 Key 和地址', async () => { + mocks.config = { + tts: { mode: 'openai' }, + openai: { instances: [{ id: 'x', name: 'X', apiKey: 'openai-key', baseUrl: 'https://proxy.example.com/v1', model: 'm' }], activeInstanceId: 'x' }, + }; + mocks.fetch.mockImplementation(async () => new Response(new Uint8Array(Buffer.from(miniMaxAudio(), 'hex')), { headers: { 'Content-Type': 'audio/pcm' } })); + const res = await post({ text: 'OpenAI 语音', language: 'zh' }); + expect(res.status).toBe(200); + const [url, init] = mocks.fetch.mock.calls[0]; + expect(url).toBe('https://proxy.example.com/v1/audio/speech'); + expect(init.headers.Authorization).toBe('Bearer openai-key'); + expect(measureLoudness(mocks.encoded[0])).toBeCloseTo(-15, 0); + }); + it('换了音色重新合成', async () => { const first = await (await post({ text: '换音色', language: 'zh' })).json(); mocks.config = { tts: { mode: 'minimax', minimax: { voice: 'other-voice' } }, minimax: { apiKey: 'mm-key' } }; diff --git a/src/__tests__/unit/tts-providers.test.ts b/src/__tests__/unit/tts-providers.test.ts index 76bcfe72..c8789fc7 100644 --- a/src/__tests__/unit/tts-providers.test.ts +++ b/src/__tests__/unit/tts-providers.test.ts @@ -2,7 +2,7 @@ * 云端语音合成:MiniMax 与千问的请求格式、默认设置、接口地址推算和错误处理 */ import { beforeEach, describe, expect, it, vi } from 'vitest'; -import { CLOUD_TTS_DEFAULTS, CLOUD_TTS_DOCS, TTS_MODES, defaultTtsEndpoint } from '@/lib/tts/constants'; +import { CLOUD_TTS_DEFAULTS, CLOUD_TTS_DOCS, TTS_MODES, defaultTtsEndpoint, getTtsChannelConfig } from '@/lib/tts/constants'; import { TtsError, resolveTtsSettings, splitJsonObjects, synthesizeWithProvider } from '@/lib/tts/providers'; import { encodeWav } from '@/lib/tts/wav'; @@ -262,3 +262,55 @@ describe('火山引擎 Agent Plan 语音合成', () => { expect(init.headers).toMatchObject({ 'X-Api-Key': 'agent-plan-key', 'X-Api-Resource-Id': 'seed-tts-2.0' }); }); }); + +describe('OpenAI 语音合成', () => { + const config = { + openai: { + instances: [ + { id: 'a', name: 'A', apiKey: 'key-a', baseUrl: 'https://proxy.example.com/v1/', model: 'm' }, + { id: 'b', name: 'B', apiKey: 'key-b', baseUrl: 'https://api.openai.com/v1', model: 'm' }, + ], + activeInstanceId: 'a', + }, + glm: { apiKey: 'glm-key' }, + }; + + it('留空 Key 时使用当前激活的 OpenAI 实例的 Key 和 Base URL;单独填写的 Key 优先', () => { + expect(getTtsChannelConfig(config, 'openai')).toEqual({ apiKey: 'key-a', baseUrl: 'https://proxy.example.com/v1/' }); + expect(getTtsChannelConfig(config, 'glm')).toEqual({ apiKey: 'glm-key' }); + expect(getTtsChannelConfig({}, 'openai')).toBeUndefined(); + + const shared = resolveTtsSettings('openai', undefined, getTtsChannelConfig(config, 'openai')); + expect(shared).toMatchObject({ apiKey: 'key-a', endpoint: 'https://proxy.example.com/v1/audio/speech', model: 'gpt-4o-mini-tts', voice: 'cedar' }); + expect(resolveTtsSettings('openai', { apiKey: 'own-key' }, getTtsChannelConfig(config, 'openai')).apiKey).toBe('own-key'); + expect(resolveTtsSettings('openai', { apiKey: 'own-key' }, undefined)).toMatchObject({ endpoint: 'https://api.openai.com/v1/audio/speech' }); + }); + + it('请求 PCM 并带语气指令,解码 24kHz 16 位 PCM', async () => { + const pcm = Buffer.alloc(4); + pcm.writeInt16LE(16384, 0); + pcm.writeInt16LE(-8192, 2); + fetchMock.mockResolvedValue(new Response(new Uint8Array(pcm), { headers: { 'Content-Type': 'audio/pcm' } })); + const settings = resolveTtsSettings('openai', { apiKey: 'own-key' }, undefined); + + const audio = await synthesizeWithProvider('第一步', 'zh', settings); + expect(audio.sampleRate).toBe(24000); + expect(Array.from(audio.samples)).toEqual([0.5, -0.25]); + expect(fetchMock.mock.calls[0][1].headers.Authorization).toBe('Bearer own-key'); + expect(requestBody()).toMatchObject({ + model: 'gpt-4o-mini-tts', input: '第一步', voice: 'cedar', response_format: 'pcm', instructions: expect.stringContaining('不要播音腔'), + }); + }); + + it('tts-1 系列不传指令;没有 Key 时报未配置;错误带上服务商说明', async () => { + fetchMock.mockResolvedValue(new Response(new Uint8Array(Buffer.alloc(2)), { headers: { 'Content-Type': 'audio/pcm' } })); + await synthesizeWithProvider('你好', 'zh', resolveTtsSettings('openai', { apiKey: 'k', model: 'tts-1-hd' }, undefined)); + expect(requestBody()).not.toHaveProperty('instructions'); + + await expect(synthesizeWithProvider('你好', 'zh', resolveTtsSettings('openai', undefined, undefined))).rejects.toMatchObject({ code: 'TTS_NOT_CONFIGURED' }); + + fetchMock.mockResolvedValueOnce(json({ error: { message: 'Incorrect API key provided', code: 'invalid_api_key' } }, 401)); + await expect(synthesizeWithProvider('你好', 'zh', resolveTtsSettings('openai', { apiKey: 'bad' }, undefined))) + .rejects.toMatchObject({ message: 'HTTP 401: invalid_api_key: Incorrect API key provided' }); + }); +}); diff --git a/src/components/settings/tts-settings.tsx b/src/components/settings/tts-settings.tsx index 4a0be062..62cd0846 100644 --- a/src/components/settings/tts-settings.tsx +++ b/src/components/settings/tts-settings.tsx @@ -17,7 +17,7 @@ import { getSpeechAudio, unlockSpeechAudio } from "@/lib/cloud-speech"; import { getApiErrorDetails, getApiErrorMessage } from "@/lib/error-message"; import { toast } from "@/lib/feedback"; import { frontendLogger } from "@/lib/frontend-logger"; -import { CLOUD_TTS_DEFAULTS, CLOUD_TTS_DOCS, TTS_MODES, defaultTtsEndpoint, hasOwnTtsApiKey, isCloudTtsProvider } from "@/lib/tts/constants"; +import { CLOUD_TTS_DEFAULTS, CLOUD_TTS_DOCS, TTS_MODES, defaultTtsEndpoint, getTtsChannelConfig, hasOwnTtsApiKey, isCloudTtsProvider } from "@/lib/tts/constants"; import type { CloudTtsSettings, TtsMode } from "@/lib/tts/constants"; import type { AppConfig } from "@/types/api"; @@ -48,7 +48,8 @@ export function TtsSettings({ config, setConfig, saving, onSave }: TtsSettingsPr }; // 豆包语音的 Key 保存在语音设置中;其他语音与对应 AI 渠道共用 Key const ownApiKey = provider ? hasOwnTtsApiKey(provider) : false; - const apiKey = provider ? (ownApiKey ? settings?.apiKey : config[provider]?.apiKey) : undefined; + const channel = provider ? getTtsChannelConfig(config, provider) : undefined; + const apiKey = ownApiKey ? settings?.apiKey : channel?.apiKey; const updateApiKey = (value: string) => { if (!provider) return; if (ownApiKey) updateSettings("apiKey", value); @@ -101,7 +102,7 @@ export function TtsSettings({ config, setConfig, saving, onSave }: TtsSettingsPr {provider && (
- + updateApiKey(e.target.value)} @@ -133,7 +134,7 @@ export function TtsSettings({ config, setConfig, saving, onSave }: TtsSettingsPr updateSettings("endpoint", e.target.value)} - placeholder={defaultTtsEndpoint(provider, config[provider])} + placeholder={defaultTtsEndpoint(provider, channel)} />

{texts.endpointHint}

diff --git a/src/lib/translations.ts b/src/lib/translations.ts index b86e264b..6a7161e9 100644 --- a/src/lib/translations.ts +++ b/src/lib/translations.ts @@ -619,6 +619,7 @@ export const translations = { stepfun: "Cloud voice: StepFun (Step Plan recommended)", volcengine: "Cloud voice: Volcengine Doubao Speech (resource pack recommended)", "volcengine-agent": "Cloud voice: Volcengine Agent Plan (Doubao speech synthesis 2.0, counts toward the plan)", + openai: "Cloud voice: OpenAI (gpt-4o-mini-tts)", }, browserHint: "Animation narration is read by the speech engine of each viewer's browser or system. The voice depends on the device, and some devices have no voice at all.", cloudHint: "The server synthesizes the narration with the provider below and normalizes it to about -15 LUFS, so every device hears the same voice. Each segment is synthesized once and then cached; synthesis uses the provider's quota.", @@ -629,6 +630,7 @@ export const translations = { stepfun: "Shared with the StepFun channel in AI settings. A Step Plan key is recommended (it includes speech synthesis; the default base URL is the Step Plan one). For a pay-as-you-go key, set the channel base URL to https://api.stepfun.com/v1.", volcengine: "Doubao Speech has its own key, separate from Volcengine Ark: enable speech synthesis 2.0 and create an API key in the Doubao Speech console (https://console.volcengine.com/speech). A resource pack or plan is recommended over pay-as-you-go.", "volcengine-agent": "Shared with the Volcengine Agent Plan channel in AI settings (the plan's dedicated API key from the Agent Plan page in the Ark console). Speech counts toward the plan quota; speech models only have daily and monthly limits.", + openai: "Optional. Leave empty to use the API key and base URL of the OpenAI configuration currently active in AI settings. Fill it in to use OpenAI for voice only.", }, model: "Speech model", voice: "Voice", @@ -639,6 +641,7 @@ export const translations = { stepfun: "Defaults to qingniandaxuesheng (young university student). The stepaudio models also get the natural, clear, no-broadcast-tone instruction. See the voice list for options supported by each model.", volcengine: "Defaults to zh_male_yangguangqingnian_uranus_bigtts (sunny young man). The speech model field is the resource ID (seed-tts-2.0 for Doubao speech synthesis 2.0 voices); the voice must match it.", "volcengine-agent": "Defaults to zh_male_yangguangqingnian_uranus_bigtts (sunny young man). The speech model field is the resource ID (seed-tts-2.0); the voice must be a Doubao speech synthesis 2.0 voice.", + openai: "Defaults to cedar, which OpenAI recommends for quality, with the natural, clear, no-broadcast-tone instruction. OpenAI voices are tuned for English, so check Chinese narration with a preview. OpenAI plans to retire gpt-4o-mini-tts and the tts-1 models on 2027-01-06.", }, endpoint: "Speech API URL (optional)", docs: "Docs", @@ -1873,6 +1876,7 @@ export const translations = { stepfun: "云端语音:阶跃星辰(建议使用 Step Plan)", volcengine: "云端语音:火山引擎豆包语音(建议购买资源包)", "volcengine-agent": "云端语音:火山引擎 Agent Plan(豆包语音合成 2.0,计入套餐额度)", + openai: "云端语音:OpenAI(gpt-4o-mini-tts)", }, browserHint: "动画讲解由观看者的浏览器或系统自带的语音朗读,音色取决于设备,部分设备没有可用语音。", cloudHint: "由服务端调用下方服务商合成讲解语音,并统一到约 -15 LUFS 的响度,所有设备听到的音色一致。每段讲解只合成一次并缓存,合成会消耗服务商额度。", @@ -1883,6 +1887,7 @@ export const translations = { stepfun: "与「AI 设置」中的阶跃星辰渠道共用。建议使用 Step Plan 套餐的 Key(套餐含语音合成,渠道默认即 Step Plan 地址);按量付费的 Key 需把渠道 Base URL 改为 https://api.stepfun.com/v1。", volcengine: "豆包语音的 Key 与火山方舟不同:在豆包语音控制台(https://console.volcengine.com/speech)开通语音合成 2.0 并创建 API Key。建议购买资源包或套餐而不是按量付费。", "volcengine-agent": "与「AI 设置」中的火山引擎 Agent Plan 渠道共用(方舟控制台 Agent Plan 管理页的专属 API Key)。语音计入套餐额度,语音模型只有日限额和月限额。", + openai: "可留空:留空时使用「AI 设置」中当前激活的 OpenAI 配置的 API Key 和 Base URL;只用 OpenAI 合成语音时在此填写。", }, model: "语音模型", voice: "音色", @@ -1893,6 +1898,7 @@ export const translations = { stepfun: "默认 qingniandaxuesheng(青年大学生),stepaudio 模型还会按指令要求自然、清晰、不用播音腔;各模型支持的音色见音色列表。", volcengine: "默认 zh_male_yangguangqingnian_uranus_bigtts(阳光青年 2.0)。「语音模型」填写资源 ID(豆包语音合成模型 2.0 的音色为 seed-tts-2.0),音色须与之对应。", "volcengine-agent": "默认 zh_male_yangguangqingnian_uranus_bigtts(阳光青年 2.0)。「语音模型」填写资源 ID(seed-tts-2.0),音色须为豆包语音合成模型 2.0 的音色。", + openai: "默认 cedar(OpenAI 推荐的高质量音色),并按指令要求自然、清晰、不用播音腔。OpenAI 的音色针对英语优化,中文讲解请先试听。OpenAI 计划于 2027-01-06 下线 gpt-4o-mini-tts 与 tts-1 系列模型。", }, endpoint: "语音接口地址(可选)", docs: "说明文档", diff --git a/src/lib/tts/constants.ts b/src/lib/tts/constants.ts index 5a9bc9b9..91863255 100644 --- a/src/lib/tts/constants.ts +++ b/src/lib/tts/constants.ts @@ -6,7 +6,7 @@ import { resolveVendorConfig } from "@/lib/ai/vendor-presets"; import type { VendorConfig } from "@/lib/ai/vendor-presets"; /** browser:浏览器本地语音(Web Speech API);其余为服务端调用对应渠道的云端语音合成 */ -export const TTS_MODES = ['browser', 'minimax', 'qwen', 'glm', 'stepfun', 'volcengine', 'volcengine-agent'] as const; +export const TTS_MODES = ['browser', 'minimax', 'qwen', 'glm', 'stepfun', 'volcengine', 'volcengine-agent', 'openai'] as const; export type TtsMode = typeof TTS_MODES[number]; export type CloudTtsProvider = Exclude; @@ -27,7 +27,8 @@ export const CLOUD_TTS_PROVIDERS = TTS_MODES.filter((mode): mode is CloudTtsProv * 默认音色:年轻男性,自然、清晰、略带科技感,不用播音腔、不模仿角色。 * MiniMax 用系统音色「精英青年」;千问用 Qwen-Audio-TTS 的男声「龙安鲁风」(25 岁,明亮开朗),再用指令约束语气; * 智谱 GLM-TTS 用「小陈」(年轻、专业);阶跃星辰用「青年大学生」,同样用指令约束语气; - * 火山引擎(豆包语音、Agent Plan)用豆包语音合成模型 2.0(资源 ID seed-tts-2.0)的「阳光青年」 + * 火山引擎(豆包语音、Agent Plan)用豆包语音合成模型 2.0(资源 ID seed-tts-2.0)的「阳光青年」; + * OpenAI 用 gpt-4o-mini-tts 与官方推荐的 cedar,同样用指令约束语气 */ export const CLOUD_TTS_DEFAULTS: Record>> = { minimax: { model: 'speech-2.8-hd', voice: 'male-qn-jingying' }, @@ -36,11 +37,33 @@ export const CLOUD_TTS_DEFAULTS: Record item.id === config.openai?.activeInstanceId); + return instance ? { apiKey: instance.apiKey, baseUrl: instance.baseUrl } : undefined; + } + return (config as Partial>)[provider]; } /** 火山引擎豆包语音的 HTTP 单向流式接口(与火山方舟的对话接口不同域名) */ @@ -81,6 +104,12 @@ export const CLOUD_TTS_DOCS: Record { + const { data, audio } = await postSpeech(settings.endpoint, settings.apiKey, { + model: settings.model, + input: text, + voice: settings.voice, + response_format: 'pcm', + ...(usesStyleInstruction('openai', settings.model) ? { instructions: VOICE_STYLE_INSTRUCTION } : {}), + }); + if (!audio) throw new TtsError('TTS_PROVIDER_ERROR', `OpenAI: ${errorMessageOf(data, 'no audio')}`); + return { sampleRate: SAMPLE_RATE, samples: pcm16ToFloat(audio) }; +} + export async function synthesizeWithProvider(text: string, language: 'zh' | 'en', settings: ResolvedTtsSettings): Promise { if (!settings.apiKey) { throw new TtsError('TTS_NOT_CONFIGURED', `${settings.provider} API key is not configured`); @@ -239,5 +256,7 @@ export async function synthesizeWithProvider(text: string, language: 'zh' | 'en' case 'volcengine': case 'volcengine-agent': return synthesizeVolcengine(text, settings); + case 'openai': + return synthesizeOpenAI(text, settings); } } diff --git a/src/lib/tts/speech-cache.ts b/src/lib/tts/speech-cache.ts index 6a3345c1..2d6a8e7b 100644 --- a/src/lib/tts/speech-cache.ts +++ b/src/lib/tts/speech-cache.ts @@ -9,7 +9,7 @@ import path from "path"; import { getAppConfig } from "@/lib/config"; import { createLogger } from "@/lib/logger"; import { MAX_NARRATION_TEXT_LENGTH, decodeXmlText, getEmbeddedNarration } from "@/lib/svg-animation"; -import { TARGET_LOUDNESS_LUFS, VOICE_STYLE_INSTRUCTION, isCloudTtsProvider, usesStyleInstruction } from "./constants"; +import { TARGET_LOUDNESS_LUFS, VOICE_STYLE_INSTRUCTION, getTtsChannelConfig, isCloudTtsProvider, usesStyleInstruction } from "./constants"; import type { CloudTtsProvider, TtsMode } from "./constants"; import { normalizeLoudness } from "./loudness"; import { encodeMp3, looksLikeMp3 } from "./mp3"; @@ -62,7 +62,7 @@ function currentSettings(): ResolvedTtsSettings | null { const config = getAppConfig(); const mode = config.tts?.mode; if (!isCloudTtsProvider(mode)) return null; - return resolveTtsSettings(mode, config.tts?.[mode], config[mode]); + return resolveTtsSettings(mode, config.tts?.[mode], getTtsChannelConfig(config, mode)); } export function speechId({ provider, model, voice, language, text }: SpeechSource): string {