0Pricing
AI Prompt Engineering · Lezione

Pattern di prompt TTS per un parlato naturale

Struttura delle frasi, punteggiatura e indicazioni sul ritmo che migliorano l’output TTS

Pattern di prompt TTS per un parlato naturale è una lezione AI Prompt Engineering gratuita su CoddyKit. Questa è la lezione 1 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento AI Prompt Engineering, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso AI Prompt Engineering include 4 lezioni in totale.

Perché il prompting per TTS è diverso

I sistemi di sintesi vocale convertono letteralmente il testo in audio. A differenza del testo visivo, che i lettori possono rileggere se una parte non è chiara, l'ascoltatore vive l'audio in modo lineare e non può fermarsi per decodificare una frase ambigua.

Scrivere per TTS significa considerare come suonano le parole: ritmo, lunghezza delle frasi, ambiguità nella pronuncia e assenza di formattazione visiva, come il grassetto o gli elenchi puntati.

Lunghezza delle frasi: meglio frasi più brevi

Le frasi lunghe e complesse, con molte proposizioni, sono difficili da seguire in audio. I sistemi TTS interrompono spesso il ritmo in punti grammaticalmente corretti, ma acusticamente innaturali. Punti a frasi di 10-20 parole per ottenere un parlato naturale.

# 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.'
)

La punteggiatura come indicatore audio

I motori TTS utilizzano la punteggiatura per controllare il ritmo:

  • Punto (.): arresto completo, pausa più lunga
  • Virgola (,): pausa breve
  • Punto interrogativo (?): intonazione ascendente
  • Punto esclamativo (!): enfasi ed energia
  • Punto e virgola (;): il comportamento varia a seconda del motore, spesso viene ignorato
  • Lineetta em (—): spesso causa pause innaturali, da evitare

Utilizzi il punto in modo esplicito, anziché la lineetta em o il punto e virgola, per controllare il ritmo in modo affidabile.

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)

Evitare le abbreviazioni ambigue

Le abbreviazioni che i lettori decodificano visivamente diventano trappole per la pronuncia errata nei sistemi TTS. I diversi motori TTS gestiscono le abbreviazioni in modo incoerente.

  • Dr. → potrebbe pronunciare 'Doctor' o 'Drive'
  • St. → 'Saint' o 'Street'?
  • vs. → 'versus' o 'vs'?
  • etc. → 'et cetera' o 'etcee'?

Scriva per esteso le abbreviazioni nel testo destinato al TTS per assicurare una pronuncia corretta.

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)

Parole che causano pronunce errate

Alcune parole o configurazioni confondono sistematicamente i motori TTS. Le riconosca e utilizzi delle alternative:

  • Omonimi grafici: 'read' (presente o passato), 'lead' (metallo o guidare), 'wind'. Il TTS sceglie una delle pronunce
  • Nomi propri rari: termini tecnici, nomi di marchi, parole straniere
  • Numeri in contesti insoliti: versioni delle API, formati delle date, unità di misura
# 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')

Numeri e date per TTS

I numeri sono una delle principali fonti di pronunce innaturali nel TTS. Li scriva in modo da non lasciare ambiguità su come devono essere pronunciati.

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
)

Rimuovere la formattazione visiva

La formattazione Markdown e HTML è invisibile all'occhio, ma alcuni motori TTS la pronunciano ad alta voce. Asterischi, simboli cancelletto e parentesi angolari devono essere rimossi o sostituiti con equivalenti pronunciabili.

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)

Gestire il ritmo con frasi di transizione

Nel testo scritto, la struttura visiva, come paragrafi e intestazioni, guida il lettore. Nell'audio TTS, sono necessarie frasi di transizione pronunciate per aiutare gli ascoltatori a seguire la struttura.

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]}')

Testare il testo per TTS

L'unico test affidabile per la qualità del TTS è ascoltare il risultato. Crei un ciclo di test e ascolto: generi il testo → lo invii all'API TTS → lo ascolti → lo perfezioni. Non si affidi alla lettura visiva del testo.

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)

Scelta della voce e corrispondenza del prompt

Le diverse voci TTS hanno punti di forza differenti. Abbini la voce al tono del contenuto:

  • Calda/narrativa: narrazione, contenuti didattici
  • Professionale/neutrale: report aziendali, documentazione tecnica
  • Energica/brillante: marketing, demo di prodotto, notifiche

Chieda all'LLM di scrivere contenuti che corrispondano al registro naturale della voce.

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])

Progettazione della pipeline da LLM a TTS

In una pipeline di produzione, un LLM genera testo che viene poi passato a un motore TTS. I due componenti devono essere coordinati: l'LLM deve sapere che sta generando testo per TTS, non per la lettura, e qualsiasi prompt di sistema o fase di post-elaborazione deve imporre regole adatte al TTS prima che il testo raggiunga l'API TTS.

Aggiunga una fase leggera di post-elaborazione tra l'output dell'LLM e l'input del TTS: rimuova il Markdown eventualmente rimasto, espanda le abbreviazioni e controlli la lunghezza delle frasi. In questo modo intercetta gli errori di formattazione dell'LLM prima che diventino artefatti audio.

Verifica: struttura delle frasi per TTS

Quale dei seguenti testi è formattato meglio per la narrazione tramite sintesi vocale?

Riepilogo: pattern di prompting TTS per un parlato naturale

Il testo TTS deve essere scritto per l'orecchio, non per l'occhio. Regole fondamentali: mantenga le frasi tra 10 e 20 parole, utilizzi solo il punto e la virgola per regolare il ritmo, scriva per esteso tutte le abbreviazioni e i numeri, rimuova ogni elemento Markdown e la formattazione visiva e utilizzi frasi di transizione pronunciate per sostituire la struttura visiva. Gli omonimi grafici, i termini tecnici e i formati numerici insoliti causano pronunce errate. Li individui e li sostituisca. Verifichi sempre il risultato ascoltando l'audio generato, non leggendo il testo.

Domande Frequenti

La lezione «Pattern di prompt TTS per un parlato naturale» è gratuita?

Sì — il testo completo di «Pattern di prompt TTS per un parlato naturale» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso AI Prompt Engineering, passa a CoddyKit PRO. Il corso AI Prompt Engineering include 4 lezioni in totale.

Cosa imparerò in «Pattern di prompt TTS per un parlato naturale»?

Struttura delle frasi, punteggiatura e indicazioni sul ritmo che migliorano l’output TTS Eserciti AI Prompt Engineering con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare AI Prompt Engineering?

Non è richiesta alcuna esperienza precedente. AI Prompt Engineering su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 1 di 4.

Quanto tempo richiede la lezione «Pattern di prompt TTS per un parlato naturale»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione AI Prompt Engineering?

Sì. Ogni lezione AI Prompt Engineering include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Pattern di prompt TTS per un parlato naturale
  2. SSML e controllo della prosodia
  3. Progettazione della persona per la Voice AI
  4. Agenti vocali e testuali multimodali
← Torna a AI Prompt Engineering