AI Prompt Engineering · 课时

适用于自然语音的 TTS 提示词模式

能够改善 TTS 输出的句子结构、标点和语速提示。

第 1 / 4 课13 个步骤

适用于自然语音的 TTS 提示词模式 是 CoddyKit 上的免费 AI Prompt Engineering 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Prompt Engineering 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Prompt Engineering 课程共包含 4 节课。

TTS 提示词为何不同

文本转语音系统会按照字面将您的文本转换为音频。与视觉文本不同,读者可以重新阅读难以理解的部分;听众是线性地接收音频的,无法暂停来解读含义模糊的句子。

为 TTS 撰写内容意味着要考虑词语的听感——节奏、句子长度、发音歧义,以及缺少粗体或项目符号等视觉格式这一事实。

句子长度:越短越好

包含多个从句的长而复杂的句子在音频中很难理解。TTS 系统经常会在语法上正确、但听感上不自然的位置打断节奏。请将句子长度控制在 10 到 20 个词,以获得自然的语音效果。

# Prompt a model to generate TTS-optimized text
TTS_SYSTEM_PROMPT = (
    'You are writing text that will be read aloud by a text-to-speech system.\n\n'
    'Rules:\n'
    '- Use short, clear sentences (10-20 words each).\n'
    '- Avoid complex nested clauses.\n'
    '- End each sentence with a period for clear pause signals.\n'
    '- Avoid parenthetical asides in the middle of sentences.\n'
    '- Use conversational vocabulary — write as you would speak.\n'
    '- Never use bullet points, headers, or markdown formatting.'
)

# Bad (long, nested):
BAD = (
    'The transformer architecture, which was introduced in the landmark 2017 paper '
    '"Attention is All You Need" by Vaswani et al. at Google, fundamentally changed '
    'natural language processing by replacing recurrence with self-attention.'
)

# Good (TTS-friendly):
GOOD = (
    'The transformer architecture changed natural language processing. '
    'It was introduced in 2017 by researchers at Google. '
    'Their key innovation was replacing recurrence with self-attention.'
)

将标点符号用作音频提示

TTS 引擎使用标点符号来控制语速和停顿:

  • 句号(.):完整停顿,停顿时间较长
  • 逗号(,):短暂停顿
  • 问号(?):语调上扬
  • 感叹号(!):强调并增强活力
  • 分号(;):行为因引擎而异,通常会被忽略
  • 破折号(—):通常会造成不自然的停顿,应避免使用

请使用明确的句号,而不是破折号或分号,以可靠地控制语速和停顿。

TTS_PUNCTUATION_PROMPT = (
    'Write the following content for text-to-speech narration. '
    'Use only periods, commas, and question marks for punctuation. '
    'Avoid em dashes, semicolons, colons, and parentheses. '
    'Break complex thoughts into multiple short sentences.\n\n'
    'Content to rewrite: {content}'
)

# Example transformation
original = (
    'There are three main factors to consider: cost, quality, and speed — '
    'and often, you can only optimize for two of them (this is sometimes '
    'called the project management triangle).'
)

for_tts = (
    'There are three main factors to consider. The first is cost. '
    'The second is quality. The third is speed. '
    'Usually, you can only optimize for two of these at once. '
    'This is sometimes called the project management triangle.'
)
print(for_tts)

避免使用含义不明确的缩写

读者可以通过视觉识别含义的缩写,可能会成为 TTS 误读的陷阱。不同的 TTS 引擎对缩写的处理方式并不一致。

  • Dr. → 可能读作“Doctor”或“Drive”
  • St. → 可能读作“Saint”或“Street”?
  • vs. → 可能读作“versus”或“vs”?
  • etc. → 可能读作“et cetera”或“etcee”?

请在 TTS 文本中拼写出缩写的完整形式,以确保发音正确。

TTS_ABBREVIATION_RULES = (
    'When writing for text-to-speech:\n'
    '- Write "Doctor" not "Dr."\n'
    '- Write "Street" or "Saint" not "St."\n'
    '- Write "versus" not "vs."\n'
    '- Write "et cetera" not "etc."\n'
    '- Write "for example" not "e.g."\n'
    '- Write "that is" not "i.e."\n'
    '- Write out years: "twenty twenty-five" not "2025" when narrated in prose\n'
    '- Write out numbers under 10: "three" not "3" in conversational text\n'
    '- Spell out acronyms on first use: '
    '"Application Programming Interface, or API"\n'
)
print(TTS_ABBREVIATION_RULES)

容易导致误读的词语

某些词语或模式经常使 TTS 引擎出错。请了解这些情况并使用替代表达:

  • 同形异音词:“read”(现在时与过去时)、“lead”(金属与引导)、“wind”——TTS 只能选择其中一种发音
  • 罕见的专有名词:技术术语、品牌名称、外语词
  • 特殊语境中的数字:API 版本、日期格式、度量值
# Prompting LLM to detect and fix TTS pronunciation issues
TTS_REVIEW_PROMPT = (
    'Review the following text for text-to-speech pronunciation issues.\n'
    'Identify words that might be mispronounced by a TTS engine because they:\n'
    '1. Are homographs with multiple pronunciations\n'
    '2. Are technical terms, brand names, or foreign words\n'
    '3. Are abbreviations or acronyms\n'
    '4. Are numbers in unusual formats\n\n'
    'For each issue, provide the original text and a TTS-safe replacement.\n\n'
    'Text to review: {text}'
)

# Example issues and fixes
ISSUES = {
    'She read the docs': 'She read (past tense - ambiguous) -> She finished reading the docs',
    'Lead developer': 'Lead (metal or guide?) -> Lead (rhymes with feed) developer',
    'API v2.3.1': 'v2.3.1 -> version 2 point 3 point 1',
    'The .env file': 'dot E N V file (may say .env) -> the environment config file',
    'Re-init': 'may say Ray-in-it -> reinitialize',
}
for problem, fix in ISSUES.items():
    print(f'Issue: {problem}\nFix: {fix}\n')

TTS 中的数字和日期

数字是 TTS 产生不自然语音的主要来源之一。请以不会对读法产生歧义的方式书写数字。

NUMBER_TTS_RULES = (
    'When writing numbers for TTS narration:\n'
    '- Dates: write "January fifteenth, 2025" not "01/15/2025"\n'
    '- Time: write "3 in the afternoon" not "15:00" in casual speech\n'
    '- Percentages: write "forty-five percent" not "45%" in narration\n'
    '- Large numbers: write "one point two million" not "1.2M"\n'
    '- Phone numbers: spell with hyphens "555-123-4567" (TTS reads each digit)\n'
    '- Currency: write "twelve dollars and fifty cents" not "$12.50" in speech\n'
    '- Fractions: write "three quarters" not "3/4"\n'
    '- Ordinals: write "first" not "1st" (TTS may say "one S T")\n'
)

# Apply when prompting the LLM to generate TTS scripts
TTS_SCRIPT_PROMPT = (
    'Write a 30-second product announcement for text-to-speech.\n'
    'Product: TaskFlow Pro, $49/month, 10,000 users worldwide, '
    'launched January 2025.\n\n'
    + NUMBER_TTS_RULES
)

移除视觉格式

Markdown 和 HTML 格式对眼睛来说是无声的,但某些 TTS 引擎会将其读出来。必须移除星号、井号和尖括号,或将它们替换为适合朗读的表达。

TTS_FORMAT_CONVERSION_PROMPT = (
    'Convert the following markdown text into plain prose suitable '
    'for text-to-speech narration.\n\n'
    'Rules:\n'
    '- Remove all markdown formatting (**, *, #, -, etc.)\n'
    '- Convert bullet lists into spoken sequences '
    '("First... Second... Third...")\n'
    '- Convert headers into topic introduction sentences\n'
    '- Remove any hyperlinks or URLs\n'
    '- Convert code snippets into descriptions '
    '("a Python function that...")\n\n'
    'Markdown text:\n'
    '{markdown_text}'
)

EXAMPLE_MARKDOWN = (
    '## Getting Started\n'
    '- Install the package with 'pip install mylib'\n'
    '- Set your **API key** in '.env'\n'
    '- Run 'python main.py' to start\n'
)

EXAMPLE_TTS = (
    'To get started, install the package using pip. '
    'Next, set your API key in your environment configuration file. '
    'Finally, run the main Python script to start.'
)
print(EXAMPLE_TTS)

使用过渡短语控制节奏

在书面文本中,视觉结构(段落、标题)会引导读者。在 TTS 音频中,您需要使用口头过渡短语,帮助听众理解内容结构。

TRANSITION_PHRASES = {
    'starting_new_topic':    ['Let us now talk about', 'Moving on to', 'Next,'],
    'adding_information':    ['Additionally,', 'Also worth noting,', 'Furthermore,'],
    'contrasting':           ['However,', 'On the other hand,', 'That said,'],
    'concluding':            ['To summarize,', 'In short,', 'To wrap up,'],
    'sequencing':            ['First,', 'Second,', 'Then,', 'Finally,'],
    'emphasizing':           ['Importantly,', 'Keep in mind that', 'Note that'],
}

TTS_STRUCTURE_PROMPT = (
    'Write a two-minute explainer on {topic} for text-to-speech narration.\n'
    'Use verbal transition phrases to guide listeners through each point. '
    'Avoid headers or bullet points. '
    'Structure the content with clear spoken signposts '
    '("First...", "Moving on...", "To summarize...").'
)

print('Available transitions:')
for category, phrases in TRANSITION_PHRASES.items():
    print(f'  {category}: {phrases[0]}')

测试您的 TTS 文本

检验 TTS 质量的唯一可靠方法是听音频。请建立“生成文本 → 发送至 TTS API → 试听 → 迭代”的测试循环。不要依赖视觉阅读文本。

import openai
import pathlib

client = openai.OpenAI(api_key='sk-...')

def generate_and_test_tts(text, output_file='test_audio.mp3'):
    """Generate TTS audio from text for auditory review."""
    response = client.audio.speech.create(
        model='tts-1-hd',
        voice='alloy',   # alloy, echo, fable, onyx, nova, shimmer
        input=text,
        speed=1.0        # 0.25 to 4.0
    )

    audio_path = pathlib.Path(output_file)
    response.stream_to_file(audio_path)
    print(f'Audio saved to {audio_path}')
    print(f'Text length: {len(text)} chars, {len(text.split())} words')
    return audio_path

# Generate and listen before shipping
tts_text = (
    'Welcome to our weekly update. '
    'This week, the engineering team shipped three major features. '
    'First, we improved search speed by forty percent. '
    'Second, we added support for twelve new languages. '
    'Third, we launched our new mobile application.'
)
path = generate_and_test_tts(tts_text)

选择语音并匹配提示词

不同的 TTS 语音各有所长。请根据内容的语气选择匹配的语音:

  • 温暖/叙事型:讲故事、教育内容
  • 专业/中性型:商业报告、技术文档
  • 充满活力/明快型:营销内容、产品演示、通知

请提示 LLM 撰写与语音自然语域相匹配的内容。

VOICE_SPECIFIC_PROMPTS = {
    'professional': (
        'Write in a clear, neutral, professional tone. '
        'Use complete sentences. Avoid contractions. '
        'Suitable for business reports and documentation.'
    ),
    'warm_narrative': (
        'Write in a warm, engaging, conversational tone. '
        'Use contractions naturally. '
        'Speak directly to the listener using "you" and "we". '
        'Suitable for educational content and storytelling.'
    ),
    'energetic': (
        'Write in an upbeat, enthusiastic tone. '
        'Use shorter sentences for impact. '
        'Include emphasis words like "amazing", "incredible", "now". '
        'Suitable for marketing and product announcements.'
    ),
}

# Select based on use case
use_case = 'warm_narrative'
print(VOICE_SPECIFIC_PROMPTS[use_case])

LLM 到 TTS 的流水线设计

在生产流水线中,LLM 会生成文本,然后将文本传递给 TTS 引擎。两者必须协调配合:LLM 必须知道自己生成的是供 TTS 使用的内容,而不是供人阅读的内容;任何系统提示词或后处理流程都必须在文本到达 TTS API 之前,强制执行适合 TTS 的规则。

请在 LLM 输出与 TTS 输入之间添加一个轻量级后处理步骤:移除遗漏的 Markdown,展开缩写,并检查句子长度。这样可以在 LLM 的格式错误变成音频瑕疵之前将其捕获。

知识检查:TTS 句子结构

下面哪一段文本最适合用于文本转语音朗读?

回顾:适合自然语音的 TTS 提示词模式

TTS 文本应当为听觉而写,而不是为视觉阅读而写。关键规则包括:将句子控制在 10 到 20 个词;只使用句号和逗号控制节奏;拼写出所有缩写和数字的完整形式;移除所有 Markdown 和视觉格式;使用口头过渡短语替代视觉结构。同形异音词、技术术语和特殊数字格式等词语会导致误读,请识别并替换它们。务必通过聆听生成的音频进行测试,而不是通过阅读文本进行测试。

免费开始

用 AI 导师学习 AI Prompt Engineering — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
53
课程
199

常见问题解答

「适用于自然语音的 TTS 提示词模式」课时是免费的吗?

是的 — 「适用于自然语音的 TTS 提示词模式」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Prompt Engineering 课程的其余内容,请升级到 CoddyKit PRO。 AI Prompt Engineering 课程共包含 4 节课。

「适用于自然语音的 TTS 提示词模式」这节课中我会学到什么?

能够改善 TTS 输出的句子结构、标点和语速提示。 你通过在浏览器中直接运行的动手代码来练习 AI Prompt Engineering,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 AI Prompt Engineering 需要有经验吗?

无需任何先前经验。CoddyKit 上的 AI Prompt Engineering 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「适用于自然语音的 TTS 提示词模式」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 AI Prompt Engineering 课中编写并运行代码吗?

能。每节 AI Prompt Engineering 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 适用于自然语音的 TTS 提示词模式
  2. SSML 与韵律控制
  3. 语音人工智能人格设计
  4. 多模态语音与文本代理
← 返回 AI Prompt Engineering