语音加 V3(只要一个 API Key)+ 各控制台快捷入口 + 对话支持 Markdown
【语音 V3:用户要的"一个 Key 搞定"那条路】 之前我给的方案是 V1(AppID + Access Token),用户问"不是只要 api key 就行了吗"—— 他是对的。查官方文档确认 V3 用 X-Api-Key,不用 appid: https://docs.volcengine.com/docs/DoubaoVoice/APIKeyUsage 实测踩到两个坑,都已写进注释: 1. 路径不能带 plan。/api/v3/plan/tts/unidirectional 是方舟 Agent Plan 专用, 语音控制台的 Key 打过去 401;/api/v3/tts/unidirectional 才通(返回真 MP3)。 2. 普通**方舟** Key 也不行,会回 `acquire failed err:call ark 401` —— 必须是语音控制台「API Key 管理」里建的那个。 三个 Key 逐个测过,结论写进了错误提示里,用户一看就知道该去哪儿拿。 V3 音色是另一套命名(zh_female_vv_uranus_bigtts),和 V1 的 BVxxx 完全不通用。 8 个音色实测都能合成,名字照官方音色列表核对。 【各控制台快捷入口】 设置页每个提供商下面多一行「去 XX 申请 API Key ↗」,语音卡片同理。 地址放在内核的一张表里(PROVIDER_CONSOLE_URLS / SPEECH_CONSOLE_URLS)而不是 写死在界面:实测 Kimi 已经从 platform.moonshot.cn 迁到 platform.kimi.com, 集中一处以后好改。每个地址都访问核实过可达。 【对话 Markdown】 自写了个轻量渲染(零依赖是这个项目的既定约束): 块级支持代码块 / 标题 / 列表 / 引用 / 分隔线,行内支持粗体斜体行内码链接删除线。 只对助手回复渲染 —— 用户输入里的 `2 * 3 * 4` 会被当成斜体,显示得和打的不一样。 【验收】 verify-speech.mjs 扩到 36 项,含 V3 音色表、命名不混用、控制台链接下发。 Node 与 Python 两份内核对拍全过 —— 这轮就是靠它抓到 Node 侧漏了 VOLC_V3_SPEAKERS。 【豆包搜索:已调通接口,但需要先开通】 接口形状摸清了(POST /api/v3/responses + tools:[{"type":"web_search"}]), 用有效方舟 Key 实测返回 403 Access denied for web search, 需要在方舟控制台「应用组件库 > 豆包搜索」开通服务后才可用。开通后即可接入。
This commit is contained in:
@@ -26,6 +26,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.*
|
||||
import androidx.compose.material3.Icon
|
||||
@@ -423,12 +424,21 @@ private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech:
|
||||
.padding(horizontal = 14.dp, vertical = 12.dp),
|
||||
) {
|
||||
when {
|
||||
msg.content.isNotBlank() -> Text(
|
||||
msg.content,
|
||||
fontSize = 16.sp,
|
||||
lineHeight = 26.sp,
|
||||
color = if (msg.error) Doubao.Error else doubaoText(),
|
||||
)
|
||||
// 助手回复按 Markdown 渲染(代码块、标题、列表、粗体…)。
|
||||
// 用户那条不渲染:用户输入里的 `2 * 3 * 4`、`_x_` 会被当成标记,
|
||||
// 显示出来跟输入的不一样会让人以为打错了。
|
||||
msg.content.isNotBlank() -> if (msg.error) {
|
||||
Text(msg.content, fontSize = 16.sp, lineHeight = 26.sp, color = Doubao.Error)
|
||||
} else {
|
||||
SelectionContainer {
|
||||
MarkdownText(
|
||||
markdown = msg.content,
|
||||
color = doubaoText(),
|
||||
fontSize = 16,
|
||||
lineHeight = 26,
|
||||
)
|
||||
}
|
||||
}
|
||||
msg.pending -> TypingDots()
|
||||
else -> Text("…", color = doubaoTextSecondary(), fontSize = 16.sp)
|
||||
}
|
||||
@@ -712,8 +722,7 @@ private fun ThinkingSheet(msg: ChatMessage, onClose: () -> Unit) {
|
||||
lineHeight = 21.sp,
|
||||
color = doubaoTextSecondary(),
|
||||
)
|
||||
}
|
||||
}
|
||||
} }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,342 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.AnnotatedString
|
||||
import androidx.compose.ui.text.SpanStyle
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.buildAnnotatedString
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextDecoration
|
||||
import androidx.compose.ui.text.withStyle
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
|
||||
/**
|
||||
* 极简 Markdown 渲染。
|
||||
*
|
||||
* 为什么自己写而不引库:
|
||||
* 项目一直坚持"零第三方依赖"(安卓端构建要能离线完成),而 Markdown 渲染
|
||||
* 在这个规模下不需要一个几百 KB 的库 —— 聊天里真正会出现的就那几种:标题、
|
||||
* 列表、粗体、行内代码、代码块、链接、引用。下面这些够用了。
|
||||
*
|
||||
* 支持:
|
||||
* 块级 ``` 代码块、# 标题、- / * / 1. 列表、> 引用、--- 分隔线、普通段落
|
||||
* 行内 **粗体**、*斜体*、`代码`、~~删除线~~、[文字](链接)
|
||||
*
|
||||
* 不支持(有意为之):表格、嵌套列表、HTML、图片。聊天里几乎不出现,
|
||||
* 而且做全了就得处理各种边界,性价比很低。
|
||||
*/
|
||||
@Composable
|
||||
fun MarkdownText(
|
||||
markdown: String,
|
||||
// ★ color 不能给默认值:默认参数里不能调用 @Composable 函数
|
||||
// (doubaoText() 是 @Composable,写成 `color: Color = doubaoText()` 直接编译不过)
|
||||
color: Color,
|
||||
modifier: Modifier = Modifier,
|
||||
linkColor: Color = Doubao.Blue,
|
||||
fontSize: Int = 16,
|
||||
lineHeight: Int = 26,
|
||||
) {
|
||||
val blocks = remember(markdown) { parseMarkdown(markdown) }
|
||||
val codeBg = if (isDark()) Color(0xFF1B1F27) else Color(0xFFF3F4F6)
|
||||
val quoteBar = Doubao.Blue.copy(alpha = 0.55f)
|
||||
|
||||
Column(modifier, verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
for (block in blocks) {
|
||||
when (block) {
|
||||
is MdBlock.Code -> {
|
||||
// 代码块单独一块:等宽字体 + 底色 + 可横向滚动(长行不折行更好读)
|
||||
Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(10.dp))
|
||||
.background(codeBg)
|
||||
.horizontalScroll(rememberScrollState())
|
||||
.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
) {
|
||||
Text(
|
||||
block.text.trimEnd(),
|
||||
fontFamily = FontFamily.Monospace,
|
||||
fontSize = (fontSize - 3).sp,
|
||||
lineHeight = (fontSize + 5).sp,
|
||||
color = color,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
is MdBlock.Quote -> {
|
||||
Row(Modifier.fillMaxWidth()) {
|
||||
// 左边一条竖线,跟正文区分开
|
||||
Box(
|
||||
Modifier
|
||||
.width(3.dp)
|
||||
.heightIn(min = 20.dp)
|
||||
.clip(RoundedCornerShape(2.dp))
|
||||
.background(quoteBar),
|
||||
)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Text(
|
||||
inline(block.text, linkColor),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = color.copy(alpha = 0.85f),
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
is MdBlock.Heading -> Text(
|
||||
inline(block.text, linkColor),
|
||||
fontSize = when (block.level) {
|
||||
1 -> (fontSize + 6).sp
|
||||
2 -> (fontSize + 3).sp
|
||||
else -> (fontSize + 1).sp
|
||||
},
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
lineHeight = (lineHeight + 4).sp,
|
||||
color = color,
|
||||
)
|
||||
|
||||
is MdBlock.Bullet -> Row(Modifier.fillMaxWidth()) {
|
||||
Text("•", fontSize = fontSize.sp, color = color.copy(alpha = 0.7f))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
inline(block.text, linkColor),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = color,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
|
||||
is MdBlock.Numbered -> Row(Modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
"${block.number}.",
|
||||
fontSize = fontSize.sp,
|
||||
color = color.copy(alpha = 0.7f),
|
||||
modifier = Modifier.width(22.dp),
|
||||
)
|
||||
Text(
|
||||
inline(block.text, linkColor),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = color,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
|
||||
is MdBlock.Divider -> Box(
|
||||
Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(vertical = 2.dp)
|
||||
.height(1.dp)
|
||||
.background(color.copy(alpha = 0.15f)),
|
||||
)
|
||||
|
||||
is MdBlock.Paragraph -> Text(
|
||||
inline(block.text, linkColor),
|
||||
fontSize = fontSize.sp,
|
||||
lineHeight = lineHeight.sp,
|
||||
color = color,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------ 块级解析 ------------------------------ */
|
||||
|
||||
internal sealed interface MdBlock {
|
||||
data class Paragraph(val text: String) : MdBlock
|
||||
data class Heading(val level: Int, val text: String) : MdBlock
|
||||
data class Bullet(val text: String) : MdBlock
|
||||
data class Numbered(val number: String, val text: String) : MdBlock
|
||||
data class Quote(val text: String) : MdBlock
|
||||
data class Code(val text: String, val lang: String = "") : MdBlock
|
||||
data object Divider : MdBlock
|
||||
}
|
||||
|
||||
private val RE_HEADING = Regex("^(#{1,6})\\s+(.*)$")
|
||||
private val RE_BULLET = Regex("^\\s*[-*+]\\s+(.*)$")
|
||||
private val RE_NUMBERED = Regex("^\\s*(\\d{1,3})[.)]\\s+(.*)$")
|
||||
private val RE_QUOTE = Regex("^\\s*>\\s?(.*)$")
|
||||
private val RE_FENCE = Regex("^\\s*```\\s*([A-Za-z0-9_+-]*)\\s*$")
|
||||
private val RE_DIVIDER = Regex("^\\s*(-{3,}|\\*{3,}|_{3,})\\s*$")
|
||||
|
||||
internal fun parseMarkdown(src: String): List<MdBlock> {
|
||||
val out = ArrayList<MdBlock>()
|
||||
val lines = src.replace("\r\n", "\n").split("\n")
|
||||
val para = StringBuilder()
|
||||
var i = 0
|
||||
|
||||
fun flushPara() {
|
||||
if (para.isNotBlank()) out.add(MdBlock.Paragraph(para.toString().trim()))
|
||||
para.setLength(0)
|
||||
}
|
||||
|
||||
while (i < lines.size) {
|
||||
val line = lines[i]
|
||||
|
||||
// 代码块:``` 开头到下一个 ```(或文件结束)
|
||||
val fence = RE_FENCE.find(line)
|
||||
if (fence != null) {
|
||||
flushPara()
|
||||
val lang = fence.groupValues[1]
|
||||
val body = StringBuilder()
|
||||
i += 1
|
||||
while (i < lines.size && RE_FENCE.find(lines[i]) == null) {
|
||||
body.append(lines[i]).append('\n')
|
||||
i += 1
|
||||
}
|
||||
i += 1 // 跳过收尾的 ```
|
||||
out.add(MdBlock.Code(body.toString(), lang))
|
||||
continue
|
||||
}
|
||||
|
||||
when {
|
||||
line.isBlank() -> flushPara()
|
||||
|
||||
RE_DIVIDER.matches(line) -> {
|
||||
flushPara()
|
||||
out.add(MdBlock.Divider)
|
||||
}
|
||||
|
||||
RE_HEADING.matches(line) -> {
|
||||
flushPara()
|
||||
val m = RE_HEADING.find(line)!!
|
||||
out.add(MdBlock.Heading(m.groupValues[1].length, m.groupValues[2].trim()))
|
||||
}
|
||||
|
||||
RE_QUOTE.matches(line) -> {
|
||||
flushPara()
|
||||
// 连续的引用行合成一段
|
||||
val q = StringBuilder()
|
||||
while (i < lines.size && RE_QUOTE.matches(lines[i])) {
|
||||
if (q.isNotEmpty()) q.append(' ')
|
||||
q.append(RE_QUOTE.find(lines[i])!!.groupValues[1])
|
||||
i += 1
|
||||
}
|
||||
out.add(MdBlock.Quote(q.toString().trim()))
|
||||
continue
|
||||
}
|
||||
|
||||
RE_BULLET.matches(line) -> {
|
||||
flushPara()
|
||||
out.add(MdBlock.Bullet(RE_BULLET.find(line)!!.groupValues[1].trim()))
|
||||
}
|
||||
|
||||
RE_NUMBERED.matches(line) -> {
|
||||
flushPara()
|
||||
val m = RE_NUMBERED.find(line)!!
|
||||
out.add(MdBlock.Numbered(m.groupValues[1], m.groupValues[2].trim()))
|
||||
}
|
||||
|
||||
else -> {
|
||||
if (para.isNotEmpty()) para.append('\n')
|
||||
para.append(line)
|
||||
}
|
||||
}
|
||||
i += 1
|
||||
}
|
||||
flushPara()
|
||||
return out
|
||||
}
|
||||
|
||||
/* ------------------------------ 行内解析 ------------------------------ */
|
||||
|
||||
/**
|
||||
* 行内标记 → AnnotatedString。
|
||||
*
|
||||
* 用一个统一的扫描器而不是一串 replace:
|
||||
* 连环 replace 会把已经生成的标记再吃一遍(比如 `**a**` 生成粗体后,
|
||||
* 里面的 `*` 又会被斜体规则匹配到),结果就是格式错乱。
|
||||
*/
|
||||
internal fun inline(text: String, linkColor: Color): AnnotatedString = buildAnnotatedString {
|
||||
var i = 0
|
||||
while (i < text.length) {
|
||||
when {
|
||||
// 行内代码:`code`
|
||||
text[i] == '`' -> {
|
||||
val end = text.indexOf('`', i + 1)
|
||||
if (end > i) {
|
||||
withStyle(SpanStyle(fontFamily = FontFamily.Monospace, fontSize = 14.sp)) {
|
||||
append(text.substring(i + 1, end))
|
||||
}
|
||||
i = end + 1
|
||||
} else {
|
||||
append(text[i]); i += 1
|
||||
}
|
||||
}
|
||||
|
||||
// 粗斜体 / 粗体 / 斜体:***x***、**x**、*x*
|
||||
text.startsWith("***", i) || text.startsWith("**", i) || text[i] == '*' -> {
|
||||
val marker = when {
|
||||
text.startsWith("***", i) -> "***"
|
||||
text.startsWith("**", i) -> "**"
|
||||
else -> "*"
|
||||
}
|
||||
val end = text.indexOf(marker, i + marker.length)
|
||||
// 找不到收尾、或者里面是空的,就当普通字符
|
||||
if (end > i + marker.length) {
|
||||
val inner = text.substring(i + marker.length, end)
|
||||
val style = when (marker) {
|
||||
"***" -> SpanStyle(fontWeight = FontWeight.Bold, fontStyle = FontStyle.Italic)
|
||||
"**" -> SpanStyle(fontWeight = FontWeight.Bold)
|
||||
else -> SpanStyle(fontStyle = FontStyle.Italic)
|
||||
}
|
||||
withStyle(style) { append(inner) }
|
||||
i = end + marker.length
|
||||
} else {
|
||||
append(text[i]); i += 1
|
||||
}
|
||||
}
|
||||
|
||||
// 删除线:~~x~~
|
||||
text.startsWith("~~", i) -> {
|
||||
val end = text.indexOf("~~", i + 2)
|
||||
if (end > i + 2) {
|
||||
withStyle(SpanStyle(textDecoration = TextDecoration.LineThrough)) {
|
||||
append(text.substring(i + 2, end))
|
||||
}
|
||||
i = end + 2
|
||||
} else {
|
||||
append(text[i]); i += 1
|
||||
}
|
||||
}
|
||||
|
||||
// 链接:[文字](地址)
|
||||
text[i] == '[' -> {
|
||||
val close = text.indexOf(']', i)
|
||||
val open = if (close > 0 && close + 1 < text.length && text[close + 1] == '(') close + 1 else -1
|
||||
val end = if (open > 0) text.indexOf(')', open) else -1
|
||||
if (close > i && open > 0 && end > open) {
|
||||
val label = text.substring(i + 1, close)
|
||||
withStyle(SpanStyle(color = linkColor, textDecoration = TextDecoration.Underline)) {
|
||||
append(label)
|
||||
}
|
||||
i = end + 1
|
||||
} else {
|
||||
append(text[i]); i += 1
|
||||
}
|
||||
}
|
||||
|
||||
else -> {
|
||||
append(text[i]); i += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
package com.doubao.lynxclone.ui
|
||||
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.widget.Toast
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
@@ -56,6 +59,7 @@ import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
@@ -111,6 +115,7 @@ fun SettingsScreen(vm: AppViewModel) {
|
||||
var showKey by remember { mutableStateOf(false) }
|
||||
// 火山 Access Token 也有自己的"看一眼"状态:跟 API Key 分开,免得一按眼睛两个框一起露
|
||||
var showVolcToken by remember { mutableStateOf(false) }
|
||||
var showVolcApiKey by remember { mutableStateOf(false) }
|
||||
|
||||
Column(Modifier.fillMaxSize()) {
|
||||
ScreenHeader("AI 内核设置", onBack = { vm.screen = Screen.Chat }) {
|
||||
@@ -192,7 +197,42 @@ fun SettingsScreen(vm: AppViewModel) {
|
||||
}
|
||||
}
|
||||
|
||||
if (draft.speech.ttsEngine == "volc") {
|
||||
if (draft.speech.ttsEngine == "volcv3") {
|
||||
// 豆包语音 V3:只要一个 API Key,音色是大模型音色(zh_xxx_bigtts)。
|
||||
// 这是"一个 Key 搞定"的那条路,放在最前面。
|
||||
Spacer(Modifier.height(12.dp))
|
||||
FormLabel("API Key")
|
||||
FormField(
|
||||
value = draft.volcApiKey,
|
||||
placeholder = if (sp.hasVolcApiKey) "已配置(留空则不变)" else "粘贴语音控制台的 API Key",
|
||||
onValue = { draft = draft.copy(volcApiKey = it) },
|
||||
password = !showVolcApiKey,
|
||||
trailing = {
|
||||
IconButton(onClick = { showVolcApiKey = !showVolcApiKey }) {
|
||||
Icon(
|
||||
if (showVolcApiKey) Icons.Filled.VisibilityOff else Icons.Filled.Visibility,
|
||||
if (showVolcApiKey) "隐藏" else "显示",
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
FormHint(
|
||||
"在语音控制台的「API Key 管理」里创建。注意:**方舟**的 Key 用不了," +
|
||||
"会报 401 —— 必须是语音这边建的 Key。",
|
||||
)
|
||||
ConsoleLink("去语音控制台创建 API Key", sp.consoleUrls["volcv3"].orEmpty())
|
||||
|
||||
Spacer(Modifier.height(12.dp))
|
||||
VoicePicker(
|
||||
title = "音色(speaker)",
|
||||
voices = vm.state.speechVoices["volcv3"].orEmpty(),
|
||||
value = draft.speech.ttsVoice,
|
||||
placeholder = "留空 = zh_female_vv_uranus_bigtts(Vivi 2.0)",
|
||||
onValue = { draft = draft.copy(speech = draft.speech.copy(ttsVoice = it)) },
|
||||
)
|
||||
FormHint("这一套音色和 V1 的 BVxxx 完全不通用,填错会报「音色不存在」。")
|
||||
} else if (draft.speech.ttsEngine == "volc") {
|
||||
Spacer(Modifier.height(12.dp))
|
||||
FormLabel("App ID")
|
||||
FormField(
|
||||
@@ -221,6 +261,7 @@ fun SettingsScreen(vm: AppViewModel) {
|
||||
},
|
||||
)
|
||||
FormHint("在火山控制台「语音技术」里创建应用后拿到 App ID 和 Access Token。")
|
||||
ConsoleLink("去火山 V1 控制台(AppID / Token)", sp.consoleUrls["volc"].orEmpty())
|
||||
|
||||
Spacer(Modifier.height(12.dp))
|
||||
VoicePicker(
|
||||
@@ -255,8 +296,11 @@ fun SettingsScreen(vm: AppViewModel) {
|
||||
"Base URL 和 Key 默认复用「连接与模型」里的设置 —— 那边没填 Key,云端朗读会失败。"
|
||||
},
|
||||
)
|
||||
ConsoleLink("去 OpenAI 申请 API Key", sp.consoleUrls["openai"].orEmpty())
|
||||
} else {
|
||||
FormHint("用系统自带语音,不联网、不需要 Key。想用豆包的音色就选「火山」。")
|
||||
FormHint("用系统自带语音,不联网、不需要 Key。想用豆包的音色就选「豆包语音」——只要一个 API Key。")
|
||||
// 设备自带那条也给个入口:想升级成云端音色时,直接送到控制台
|
||||
ConsoleLink("想用豆包音色?去语音控制台拿 API Key", sp.consoleUrls["volcv3"].orEmpty())
|
||||
}
|
||||
|
||||
// 语速只对云端引擎有效:系统 TTS 的语速归系统管,内核根本不参与合成
|
||||
@@ -339,6 +383,12 @@ fun SettingsScreen(vm: AppViewModel) {
|
||||
)
|
||||
FormHint(if (s.hasApiKey) "已配置密钥;留空保存不会覆盖它。" else "也可以写在内核数据目录的 .env 里。")
|
||||
|
||||
// 快捷入口:直达这家控制台的「申请 API Key」页
|
||||
ConsoleLink(
|
||||
"去 ${vm.state.providers[draft.provider]?.label ?: draft.provider} 申请 API Key",
|
||||
vm.state.providers[draft.provider]?.consoleUrl.orEmpty(),
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(12.dp))
|
||||
FormLabel("模型")
|
||||
FormField(
|
||||
@@ -478,10 +528,14 @@ fun SettingsScreen(vm: AppViewModel) {
|
||||
|
||||
/* ---------------------------- 语音卡片的零件 ---------------------------- */
|
||||
|
||||
/** 朗读引擎(key 跟内核 speech.ttsEngine 一致:system / volc / openai) */
|
||||
/** 朗读引擎(key 跟内核 speech.ttsEngine 一致:system / volc / volcv3 / openai) */
|
||||
private val TtsEngines: List<Pair<String, String>> = listOf(
|
||||
"system" to "设备自带",
|
||||
"volc" to "火山(豆包音色)",
|
||||
// 两个火山是两套东西,标签必须写清楚,否则用户永远分不清该选哪个:
|
||||
// volcv3 = 只要一个 API Key(推荐)
|
||||
// volc = 老接口,要 AppID + Access Token
|
||||
"volcv3" to "豆包语音(只要 API Key)",
|
||||
"volc" to "火山 V1(AppID+Token)",
|
||||
"openai" to "OpenAI 兼容",
|
||||
)
|
||||
|
||||
@@ -491,6 +545,42 @@ private val SttEngines: List<Pair<String, String>> = listOf(
|
||||
"openai" to "OpenAI(Whisper)",
|
||||
)
|
||||
|
||||
/**
|
||||
* 「去申请 Key ↗」快捷入口。
|
||||
*
|
||||
* 与其让用户自己去找控制台,不如直接送到那一页 —— 这些地址由内核下发
|
||||
* (PROVIDER_CONSOLE_URLS / SPEECH_CONSOLE_URLS),以后地址变了只改内核一处。
|
||||
*
|
||||
* url 为空就整行不画:本地部署(Ollama)不需要 Key,画一个点不动的链接更糟。
|
||||
*/
|
||||
@Composable
|
||||
private fun ConsoleLink(text: String, url: String) {
|
||||
if (url.isBlank()) return
|
||||
val ctx = LocalContext.current
|
||||
Row(
|
||||
Modifier
|
||||
.clip(RoundedCornerShape(8.dp))
|
||||
.clickable {
|
||||
try {
|
||||
ctx.startActivity(
|
||||
Intent(Intent.ACTION_VIEW, Uri.parse(url))
|
||||
// 从 Compose 起 Activity 有可能不在 Activity 上下文里,加这个 flag 更稳
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
// 没有浏览器、或者 ROM 拦了 Intent:不能崩,提示一下就行
|
||||
Toast.makeText(ctx, "打不开:$url", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
.padding(vertical = 5.dp, horizontal = 2.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(text, color = Doubao.Blue, fontSize = 13.sp)
|
||||
Spacer(Modifier.width(3.dp))
|
||||
Text("↗", color = Doubao.Blue, fontSize = 13.sp, fontWeight = FontWeight.Medium)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 语音卡片里的胶囊 chip:引擎选择、音色选择都用它。
|
||||
*
|
||||
@@ -915,6 +1005,11 @@ internal data class SettingsDraft(
|
||||
* 所以它不参与 diff,只有"用户真敲了非空且不像掩码"时才进补丁。
|
||||
*/
|
||||
val volcToken: String,
|
||||
/**
|
||||
* 豆包语音 V3 的 API Key。和 volcToken 一样永远从空开始、不参与 diff ——
|
||||
* 接口只回掩码,回填就等于用八个点覆盖真 Key。
|
||||
*/
|
||||
val volcApiKey: String,
|
||||
) {
|
||||
/**
|
||||
* 切提供商时顺带把 baseUrl / model 换成新提供商的预设。
|
||||
@@ -975,6 +1070,7 @@ internal data class SettingsDraft(
|
||||
// ★ 密钥:空白 = 不改,掩码 = 也不改。openaiApiKey 界面没有入口(复用对话那把 Key),
|
||||
// 所以它压根不进草稿 —— 这比"进了草稿再过滤掉"更保险
|
||||
secretOrNull(volcToken)?.let { sp["volcToken"] = it }
|
||||
secretOrNull(volcApiKey)?.let { sp["volcApiKey"] = it }
|
||||
// 界面没有入口的键(volcCluster / volcEncoding / openaiBaseUrl)故意不参与 diff:
|
||||
// 它们只可能来自配置文件或环境变量,界面不该在任何情况下把它们改掉
|
||||
if (sp.isNotEmpty()) patch["speech"] = sp
|
||||
@@ -1005,6 +1101,7 @@ internal data class SettingsDraft(
|
||||
sttEngine = normalizeEngine(s.speech.sttEngine, SttEngines.map { it.first }),
|
||||
),
|
||||
volcToken = "",
|
||||
volcApiKey = "",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -388,6 +388,7 @@ class KernelHandler(BaseHTTPRequestHandler):
|
||||
'speech': speech.speech_state(settings),
|
||||
'speechVoices': {
|
||||
'volc': speech.VOLC_VOICES,
|
||||
'volcv3': speech.VOLC_V3_SPEAKERS,
|
||||
'openai': speech.OPENAI_VOICES,
|
||||
'system': [],
|
||||
},
|
||||
|
||||
@@ -135,6 +135,29 @@ PROVIDER_PRESETS = {
|
||||
},
|
||||
}
|
||||
|
||||
# 各家控制台「申请 API Key」的直达链接。
|
||||
#
|
||||
# 为什么单独一张表、而不是塞进每个预设里:这些地址会变
|
||||
# (实测 Kimi 已经从 platform.moonshot.cn 迁到 platform.kimi.com,
|
||||
# 旧地址 301 跳过去),集中一处以后好改。
|
||||
# 已逐个访问核实过可达(返回 200 或 302 到登录页都算通)。
|
||||
PROVIDER_CONSOLE_URLS = {
|
||||
'ark': 'https://console.volcengine.com/ark/region:cn-beijing/apiKey',
|
||||
'openai': 'https://platform.openai.com/api-keys',
|
||||
'deepseek': 'https://platform.deepseek.com/api_keys',
|
||||
'kimi': 'https://platform.kimi.com/console/api-keys',
|
||||
'zhipu': 'https://open.bigmodel.cn/usercenter/apikeys',
|
||||
'dashscope': 'https://bailian.console.aliyun.com/?apiKey=1',
|
||||
'siliconflow': 'https://cloud.siliconflow.cn/account/ak',
|
||||
'openrouter': 'https://openrouter.ai/keys',
|
||||
'ollama': 'https://ollama.com/download',
|
||||
'custom': '',
|
||||
}
|
||||
for _key, _url in PROVIDER_CONSOLE_URLS.items():
|
||||
if _key in PROVIDER_PRESETS:
|
||||
PROVIDER_PRESETS[_key]['consoleUrl'] = _url
|
||||
|
||||
|
||||
DEFAULT_SETTINGS = {
|
||||
'provider': 'ark',
|
||||
'baseUrl': PROVIDER_PRESETS['ark']['baseUrl'],
|
||||
|
||||
@@ -34,6 +34,19 @@ DEFAULT_TIMEOUT_STT = 120
|
||||
# (鉴权头那个分号、body 的层级,光看代码容易自我说服,实测才算数)
|
||||
VOLC_TTS_URL = os.environ.get('DOUBAO_VOLC_TTS_URL') or 'https://openspeech.bytedance.com/api/v1/tts'
|
||||
|
||||
# 火山「豆包语音」V3 接口。★ 和 V1 是两套东西:
|
||||
# V1 openspeech/api/v1/tts 鉴权:appid + access_token(Bearer; 分号)
|
||||
# V3 openspeech/api/v3/tts/... 鉴权:**只要一个 API Key**(X-Api-Key)
|
||||
# 用户问"不是只要 api key 就行了吗"——对,走的就是这条。
|
||||
#
|
||||
# ★ 注意路径里**没有 plan**:/api/v3/tts/unidirectional 才是语音控制台 API Key 能用的;
|
||||
# /api/v3/plan/tts/unidirectional 是方舟 Agent Plan 专用,拿普通 Key 打会 401。
|
||||
# 实测:同一个 Key,plan 路径 401、非 plan 路径 200 且返回真 MP3。
|
||||
# 文档:https://docs.volcengine.com/docs/DoubaoVoice/APIKeyUsage
|
||||
VOLC_V3_TTS_URL = os.environ.get('DOUBAO_VOLC_V3_TTS_URL') or \
|
||||
'https://openspeech.bytedance.com/api/v3/tts/unidirectional'
|
||||
VOLC_V3_RESOURCE_ID = 'seed-tts-2.0'
|
||||
|
||||
# 火山的 encoding -> MIME。文档里 mp3/wav/ogg_opus/pcm 是常用的几个
|
||||
VOLC_MIME = {
|
||||
'mp3': 'audio/mpeg',
|
||||
@@ -99,11 +112,101 @@ def synthesize(text: str, settings: dict) -> dict:
|
||||
|
||||
if engine == 'volc':
|
||||
return _synthesize_volc(content, speech, speed)
|
||||
if engine == 'volcv3':
|
||||
return _synthesize_volc_v3(content, speech, speed)
|
||||
if engine == 'openai':
|
||||
return _synthesize_openai(content, settings, speech, speed)
|
||||
return {'engine': 'system'}
|
||||
|
||||
|
||||
def _synthesize_volc_v3(text: str, speech: dict, speed: float) -> dict:
|
||||
"""
|
||||
豆包语音 V3 合成。
|
||||
|
||||
和 V1 的区别(用户最容易搞混的地方):
|
||||
- **只要一个 API Key**(语音控制台 → API Key 管理里创建),不需要 AppID / Access Token;
|
||||
- 音色是另一套命名:`zh_female_vv_uranus_bigtts`,不是 V1 的 `BV700_streaming`;
|
||||
- 返回是**逐行 JSON**(NDJSON),每行一段 base64 音频,`code=20000000` 表示结束。
|
||||
|
||||
两个实测踩过的坑:
|
||||
1. 路径别带 plan。`/api/v3/plan/...` 是方舟 Agent Plan 专用,普通语音 Key 打过去 401;
|
||||
2. 普通**方舟** Key 也不行 —— 会回 `acquire failed err:call ark ... 401`。
|
||||
必须是**语音控制台**里那个 API Key(console.volcengine.com/speech → API Key 管理)。
|
||||
"""
|
||||
api_key = (speech.get('volcApiKey') or '').strip()
|
||||
speaker = (speech.get('ttsVoice') or '').strip() or 'zh_female_vv_uranus_bigtts'
|
||||
fmt = (speech.get('volcEncoding') or 'mp3').strip() or 'mp3'
|
||||
if fmt not in ('mp3', 'wav', 'ogg_opus', 'pcm'):
|
||||
fmt = 'mp3'
|
||||
|
||||
if not api_key:
|
||||
raise SpeechError(
|
||||
'豆包语音 V3 需要一个 API Key:语音控制台 →(左侧)API Key → 创建 API Key。'
|
||||
'注意不是方舟的 Key —— 方舟 Key 打这个接口会被判 401。'
|
||||
)
|
||||
|
||||
body = {
|
||||
'req_params': {
|
||||
'text': text,
|
||||
'speaker': speaker,
|
||||
'audio_params': {
|
||||
'format': fmt,
|
||||
# 24k 是大模型音色的标准采样率,调低会明显发闷
|
||||
'sample_rate': 24000,
|
||||
# V3 的语速是 ±100 的百分比,不是倍率(实测 -50 变慢、+50 变快)
|
||||
'speech_rate': int(round((speed - 1.0) * 100)),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
data = json.dumps(body, ensure_ascii=False).encode('utf-8')
|
||||
req = urllib.request.Request(VOLC_V3_TTS_URL, data=data, method='POST')
|
||||
req.add_header('Content-Type', 'application/json')
|
||||
req.add_header('X-Api-Key', api_key)
|
||||
req.add_header('X-Api-Resource-Id', VOLC_V3_RESOURCE_ID)
|
||||
req.add_header('X-Control-Require-Usage-Tokens-Return', '*')
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_TTS) as resp:
|
||||
raw = resp.read()
|
||||
except urllib.error.HTTPError as exc:
|
||||
detail = ''
|
||||
try:
|
||||
detail = exc.read().decode('utf-8', 'replace')[:400]
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
raise SpeechError(f'HTTP {exc.code} {detail or exc.reason}') from exc
|
||||
except urllib.error.URLError as exc:
|
||||
raise SpeechError(f'连不上:{exc.reason}') from exc
|
||||
|
||||
# 逐行解析:每行一个 JSON,拼 data 里的音频片段
|
||||
chunks = []
|
||||
error = None
|
||||
for line in raw.decode('utf-8', 'replace').splitlines():
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
item = json.loads(line)
|
||||
except Exception: # noqa: BLE001
|
||||
continue
|
||||
code = item.get('code', 0)
|
||||
payload = item.get('data')
|
||||
if isinstance(payload, str) and payload:
|
||||
chunks.append(payload)
|
||||
if code == 20000000:
|
||||
break
|
||||
if isinstance(code, int) and code > 0 and code != 20000000:
|
||||
error = f'code={code} {item.get("message") or item.get("msg") or ""}'.strip()
|
||||
break
|
||||
|
||||
if error:
|
||||
raise SpeechError(f'火山 V3 失败:{error}')
|
||||
if not chunks:
|
||||
raise SpeechError('火山 V3 没返回音频数据')
|
||||
return {'engine': 'volcv3', 'mime': VOLC_MIME.get(fmt, 'audio/mpeg'), 'audio': ''.join(chunks)}
|
||||
|
||||
|
||||
def _synthesize_volc(text: str, speech: dict, speed: float) -> dict:
|
||||
"""
|
||||
火山语音合成。
|
||||
@@ -302,12 +405,29 @@ def speech_state(settings: dict) -> dict:
|
||||
'volcCluster': speech.get('volcCluster') or 'volcano_tts',
|
||||
'volcEncoding': speech.get('volcEncoding') or 'mp3',
|
||||
'hasVolcToken': bool(speech.get('volcToken')),
|
||||
# V3 只要这一个 Key,所以界面按它判断"配没配"
|
||||
'hasVolcApiKey': bool(speech.get('volcApiKey')),
|
||||
'hasOpenaiKey': bool(speech.get('openaiApiKey') or (settings or {}).get('apiKey')),
|
||||
'openaiBaseUrl': speech.get('openaiBaseUrl') or '',
|
||||
'ttsModel': speech.get('ttsModel') or 'tts-1',
|
||||
# 各家「申请语音 Key」的直达链接,界面上做成快捷入口。
|
||||
# 这里放内核而不是写死在界面里:以后加厂商只改一处。
|
||||
'consoleUrls': SPEECH_CONSOLE_URLS,
|
||||
}
|
||||
|
||||
|
||||
# 语音相关控制台的直达链接(都已访问核实可达)
|
||||
SPEECH_CONSOLE_URLS = {
|
||||
# V3:语音控制台 → API Key 管理。**这是"只要一个 API Key"那条路的入口**
|
||||
'volcv3': 'https://console.volcengine.com/speech/new/setting/apikeys',
|
||||
# V1:同一个控制台,但拿的是 AppID + Access Token(在「语音合成」应用详情里)
|
||||
'volc': 'https://console.volcengine.com/speech/app',
|
||||
'openai': 'https://platform.openai.com/api-keys',
|
||||
# 方舟 Agent Plan:另一条能用 API Key 的路(和语音控制台不是一回事)
|
||||
'agentPlan': 'https://ark.volcengine.com/region:cn-beijing/openManagement?advancedActiveKey=agentPlan',
|
||||
}
|
||||
|
||||
|
||||
# 默认值:Android 端 Kotlin 侧也用不到这个,但 Node/Python 必须一致
|
||||
DEFAULT_SPEECH = {
|
||||
'ttsEngine': 'system',
|
||||
@@ -319,6 +439,7 @@ DEFAULT_SPEECH = {
|
||||
'sttLanguage': '',
|
||||
'volcAppId': '',
|
||||
'volcToken': '',
|
||||
'volcApiKey': '', # V3 用的那个(语音控制台 → API Key 管理)
|
||||
'volcCluster': 'volcano_tts',
|
||||
'volcEncoding': 'mp3',
|
||||
'openaiApiKey': '',
|
||||
@@ -357,10 +478,26 @@ OPENAI_VOICES = [
|
||||
{'value': 'sage', 'label': 'sage(女声,沉稳)'},
|
||||
]
|
||||
|
||||
# V3(大模型音色)的 speaker。★ 名字照官方「音色列表」核对过。
|
||||
# 这一套和 V1 的 BVxxx 完全不通用 —— 拿 BV700_streaming 去 V3 会报音色不存在。
|
||||
# 下面这 8 个是实测能合成出真 MP3 的(2026-10 验证)。
|
||||
VOLC_V3_SPEAKERS = [
|
||||
{'value': 'zh_female_vv_uranus_bigtts', 'label': 'Vivi 2.0(女声,默认)'},
|
||||
{'value': 'zh_female_cancan_uranus_bigtts', 'label': '知性灿灿 2.0'},
|
||||
{'value': 'zh_female_xiaohe_uranus_bigtts', 'label': '小何 2.0'},
|
||||
{'value': 'zh_female_tianmeixiaoyuan_uranus_bigtts', 'label': '甜美小源 2.0'},
|
||||
{'value': 'zh_female_shuangkuaisisi_uranus_bigtts', 'label': '爽快思思 2.0'},
|
||||
{'value': 'zh_male_qingcang_uranus_bigtts', 'label': '擎苍 2.0(男声)'},
|
||||
{'value': 'zh_male_m191_uranus_bigtts', 'label': '云舟 2.0'},
|
||||
{'value': 'zh_male_taocheng_uranus_bigtts', 'label': '小天 2.0'},
|
||||
]
|
||||
|
||||
|
||||
def voice_options(engine: str):
|
||||
if engine == 'volc':
|
||||
return VOLC_VOICES
|
||||
if engine == 'volcv3':
|
||||
return VOLC_V3_SPEAKERS
|
||||
if engine == 'openai':
|
||||
return OPENAI_VOICES
|
||||
return []
|
||||
|
||||
@@ -114,6 +114,7 @@ def mask_settings(settings: dict) -> dict:
|
||||
out['hasApiKey'] = bool(settings.get('apiKey'))
|
||||
speech = dict(out.get('speech') or {})
|
||||
speech['volcToken'] = '••••••••' if speech.get('volcToken') else ''
|
||||
speech['volcApiKey'] = '••••••••' if speech.get('volcApiKey') else ''
|
||||
speech['openaiApiKey'] = '••••••••' if speech.get('openaiApiKey') else ''
|
||||
out['speech'] = speech
|
||||
return out
|
||||
@@ -189,7 +190,7 @@ def write_settings(patch: dict) -> dict:
|
||||
speech_next = nxt.get('speech')
|
||||
if isinstance(speech_next, dict):
|
||||
speech_cur = current.get('speech') or {}
|
||||
for secret in ('volcToken', 'openaiApiKey'):
|
||||
for secret in ('volcToken', 'volcApiKey', 'openaiApiKey'):
|
||||
if speech_next.get(secret) == '••••••••':
|
||||
speech_next[secret] = speech_cur.get(secret, '')
|
||||
# ★ 语音里"空字符串就等于坏掉"的字段,同样不许被空值覆盖。
|
||||
|
||||
Reference in New Issue
Block a user