Generare musica con Lyria 3

Lyria 3 è la famiglia di modelli di generazione musicale di Google, disponibile tramite l'API Gemini. Con Lyria 3 puoi generare audio stereo di alta qualità a 44,1 kHz a partire da prompt di testo o immagini. Questi modelli offrono coerenza strutturale, tra cui voci, testi sincronizzati e arrangiamenti strumentali completi.

La famiglia Lyria 3 include due modelli:

Modello ID modello Ideale per Durata Output
Lyria 3 Clip lyria-3-clip-preview Clip brevi, loop, anteprime 30 secondi MP3
Lyria 3 Pro lyria-3-pro-preview Brani completi con strofe, ritornelli e ponti Un paio di minuti (controllabile tramite prompt) MP3

Entrambi i modelli possono essere utilizzati con la nuova API Interactions, supportano input multimodali (testo e immagini) e producono audio stereo ad alta fedeltà a 44,1 kHz.

Generare un clip musicale

Il modello Lyria 3 Clip genera sempre un clip di 30 secondi. Per generare un clip, chiama il metodo interactions.create con un prompt di testo. La risposta include sempre il testo e la struttura della canzone generati insieme all'audio nello schema steps.

Python

import base64
from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="lyria-3-clip-preview",
    input="Create a 30-second cheerful acoustic folk song with guitar and harmonica.",
)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "audio":
                print(f"Generated audio with mime_type: {content_block.mime_type}")
                with open("music.mp3", "wb") as f:
                    f.write(base64.b64decode(content_block.data))
            elif content_block.type == "text":
                print(f"Lyrics: {content_block.text}")

JavaScript

import { GoogleGenAI } from '@google/genai';
import * as fs from 'fs';

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
    model: 'lyria-3-clip-preview',
    input: 'Create a 30-second cheerful acoustic folk song with ' +
           'guitar and harmonica.',
});

for (const step of interaction.steps) {
    if (step.type === 'model_output') {
        for (const contentBlock of step.content) {
            if (contentBlock.type === 'audio') {
                console.log(`Generated audio with mime_type: ${contentBlock.mimeType}`);
                fs.writeFileSync('music.mp3', Buffer.from(contentBlock.data, 'base64'));
            } else if (contentBlock.type === 'text') {
                console.log(`Lyrics: ${contentBlock.text}`);
            }
        }
    }
}

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "lyria-3-clip-preview",
    "input": "Create a 30-second cheerful acoustic folk song with guitar and harmonica."
}'

Generare un brano completo

Utilizza il modello lyria-3-pro-preview per generare brani di lunga durata che durano un paio di minuti. Il modello Pro comprende la struttura musicale e può creare composizioni con strofe, ritornelli e ponti distinti. Puoi influenzare la durata specificandola nel prompt (ad es. "crea una canzone di 2 minuti") o utilizzando i timestamp per definire la struttura.

Python

interaction = client.interactions.create(
    model="lyria-3-pro-preview",
    input="An epic cinematic orchestral piece about a journey home. Starts with a solo piano intro, builds through sweeping strings, and climaxes with a massive wall of sound.",
)

JavaScript

const interaction = await client.interactions.create({
    model: 'lyria-3-pro-preview',
    input: 'An epic cinematic orchestral piece about a journey home. ' +
           'Starts with a solo piano intro, builds through sweeping ' +
           'strings, and climaxes with a massive wall of sound.',
});

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "model": "lyria-3-pro-preview",
    "input": "An epic cinematic orchestral piece about a journey home. Starts with a solo piano intro, builds through sweeping strings, and climaxes with a massive wall of sound."
}'

Seleziona il formato di output

Per impostazione predefinita, i modelli Lyria 3 generano audio in formato MP3. Per Lyria 3 Pro, puoi anche richiedere l'output in formato WAV impostando response_mime_type.

Python

interaction = client.interactions.create(
    model="lyria-3-pro-preview",
    input="An atmospheric ambient track.",
    response_modalities=["audio", "text"],
    response_mime_type="audio/wav",
)

JavaScript

const interaction = await client.interactions.create({
    model: 'lyria-3-pro-preview',
    input: 'An atmospheric ambient track.',
    responseModalities: ["audio", "text"],
    responseMimeType: "audio/wav",
});

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "lyria-3-pro-preview",
    "input": "An atmospheric ambient track.",
    "responseModalities": ["audio", "text"],
    "responseMimeType": "audio/wav"
  }'

Analizzare la risposta

La risposta di Lyria 3 contiene più blocchi di contenuti all'interno dello schema steps. Le interazioni restituiscono una sequenza di passaggi, in cui i passaggi model_output contengono i contenuti generati. I blocchi di contenuti di testo contengono i testi generati o una descrizione JSON della struttura del brano. I blocchi di contenuti di tipo audio contengono i dati audio codificati in base64.

Python

lyrics = []
audio_data = None

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "audio":
                audio_data = base64.b64decode(content_block.data)
            elif content_block.type == "text":
                lyrics.append(content_block.text)

if lyrics:
    print("Lyrics:\n" + "\n".join(lyrics))

if audio_data:
    with open("output.mp3", "wb") as f:
        f.write(audio_data)

JavaScript

const lyrics = [];
let audioData = null;

for (const step of interaction.steps) {
    if (step.type === 'model_output') {
        for (const contentBlock of step.content) {
            if (contentBlock.type === 'audio') {
                audioData = Buffer.from(contentBlock.data, 'base64');
            } else if (contentBlock.type === 'text') {
                lyrics.push(contentBlock.text);
            }
        }
    }
}

if (lyrics.length) {
    console.log("Lyrics:\n" + lyrics.join("\n"));
}

if (audioData) {
    fs.writeFileSync("output.mp3", audioData);
}

REST

# The output from the REST API is a JSON object containing base64 encoded data.
# You can extract the text or the audio data using a tool like jq.
# To extract the audio and save it to a file:
curl ... | jq -r '.steps[] | select(.type=="model_output") | .content[] | select(.type=="audio") | .data' | base64 -d > output.mp3

Generare musica dalle immagini

Lyria 3 supporta input multimodali: puoi fornire fino a 10 immagini insieme al prompt di testo nell'elenco input e il modello comporrà musica ispirata ai contenuti visivi.

Python

uploaded_image = client.files.upload(file="desert_sunset.jpg")

response = client.interactions.create(
    model="lyria-3-pro-preview",
    input=[
        {"type": "text", "text": "An atmospheric ambient track inspired by the mood and colors in this image."},
        {
            "type": "image",
            "uri": uploaded_image.uri,
            "mime_type": uploaded_image.mime_type
        }
    ],
)

JavaScript

const uploadedImage = await client.files.upload({
    file: "desert_sunset.jpg",
    config: { mimeType: "image/jpeg" }
});

const interaction = await client.interactions.create({
    model: 'lyria-3-pro-preview',
    input: [
        { type: 'text', text: 'An atmospheric ambient track inspired by the mood and colors in this image.' },
        {
            type: 'image',
            uri: uploadedImage.uri,
            mimeType: uploadedImage.mimeType
        }
    ],
});

REST

# First upload the image using the Files API, then use the URI:
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "lyria-3-pro-preview",
    "input": [
      {"type": "text", "text": "An atmospheric ambient track inspired by the mood and colors in this image."},
      {"type": "image", "uri": "YOUR_FILE_URI", "mime_type": "image/jpeg"}
    ]
  }'

Fornire testi personalizzati

Puoi scrivere i tuoi testi e includerli nel prompt. Utilizza i tag di sezione come [Verse], [Chorus] e [Bridge] per aiutare il modello a comprendere la struttura del brano:

Python

prompt = """
Create a dreamy indie pop song with the following lyrics:

[Verse 1]
Walking through the neon glow,
city lights reflect below,
every shadow tells a story,
every corner, fading glory.

[Chorus]
We are the echoes in the night,
burning brighter than the light,
hold on tight, don't let me go,
we are the echoes down below.

[Verse 2]
Footsteps lost on empty streets,
rhythms sync to heartbeats,
whispers carried by the breeze,
dancing through the autumn leaves.
"""

interaction = client.interactions.create(
    model="lyria-3-pro-preview",
    input=prompt,
)

JavaScript

const prompt = `
Create a dreamy indie pop song with the following lyrics:

[Verse 1]
Walking through the neon glow,
city lights reflect below,
every shadow tells a story,
every corner, fading glory.

[Chorus]
We are the echoes in the night,
burning brighter than the light,
hold on tight, don't let me go,
we are the echoes down below.

[Verse 2]
Footsteps lost on empty streets,
rhythms sync to heartbeats,
whispers carried by the breeze,
dancing through the autumn leaves.
`;

const interaction = await client.interactions.create({
    model: 'lyria-3-pro-preview',
    input: prompt,
});

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "lyria-3-pro-preview",
    "input": "Create a dreamy indie pop song with the following lyrics: ..."
  }'

Controllare la tempistica e la struttura

Puoi specificare esattamente cosa succede in momenti specifici del brano utilizzando i timestamp. Questo è utile per controllare quando entrano gli strumenti, quando vengono fornite le parole e come procede la canzone:

Python

prompt = """
[0:00 - 0:10] Intro: Begin with a soft lo-fi beat and muffled
              vinyl crackle.
[0:10 - 0:30] Verse 1: Add a warm Fender Rhodes piano melody
              and gentle vocals singing about a rainy morning.
[0:30 - 0:50] Chorus: Full band with upbeat drums and soaring
              synth leads. The lyrics are hopeful and uplifting.
[0:50 - 1:00] Outro: Fade out with the piano melody alone.
"""

interaction = client.interactions.create(
    model="lyria-3-pro-preview",
    input=prompt,
)

JavaScript

const prompt = `
[0:00 - 0:10] Intro: Begin with a soft lo-fi beat and muffled
              vinyl crackle.
[0:10 - 0:30] Verse 1: Add a warm Fender Rhodes piano melody
              and gentle vocals singing about a rainy morning.
[0:30 - 0:50] Chorus: Full band with upbeat drums and soaring
              synth leads. The lyrics are hopeful and uplifting.
[0:50 - 1:00] Outro: Fade out with the piano melody alone.
`;

const interaction = await client.interactions.create({
    model: 'lyria-3-pro-preview',
    input: prompt,
});

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "lyria-3-pro-preview",
    "input": "[0:00 - 0:10] Intro: ..."
  }'

Generare tracce strumentali

Per la musica di sottofondo, le colonne sonore dei giochi o qualsiasi caso d'uso in cui non sono richieste le parti vocali, puoi chiedere al modello di produrre tracce solo strumentali:

Python

interaction = client.interactions.create(
    model="lyria-3-clip-preview",
    input="A bright chiptune melody in C Major, retro 8-bit video game style. Instrumental only, no vocals.",
)

JavaScript

const interaction = await client.interactions.create({
    model: 'lyria-3-clip-preview',
    input: 'A bright chiptune melody in C Major, retro 8-bit video game style. Instrumental only, no vocals.',
});

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "lyria-3-clip-preview",
    "input": "A bright chiptune melody in C Major, retro 8-bit video game style. Instrumental only, no vocals."
  }'

Generare musica in lingue diverse

Lyria 3 genera i testi nella lingua del prompt. Per generare una canzone con un testo in francese, scrivi il prompt in francese. Il modello adatta lo stile vocale e la pronuncia in base alla lingua.

Python

interaction = client.interactions.create(
    model="lyria-3-pro-preview",
    input="Crée une chanson pop romantique en français sur un coucher de soleil à Paris. Utilise du piano et de la guitare acoustique.",
)

JavaScript

const interaction = await client.interactions.create({
    model: 'lyria-3-pro-preview',
    input: 'Crée une chanson pop romantique en français sur un coucher de soleil à Paris. Utilise du piano et de la guitare acoustique.',
});

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "lyria-3-pro-preview",
    "input": "Crée une chanson pop romantique en français sur un coucher de soleil à Paris. Utilise du piano et de la guitare acoustique."
  }'

Model Intelligence

Lyria 3 analizza la procedura di prompt in cui il modello ragiona sulla struttura musicale (intro, strofa, ritornello, bridge e così via) in base al prompt. Ciò avviene prima della generazione dell'audio e garantisce la coerenza strutturale e la musicalità.

Guida ai prompt

Più specifico è il prompt, migliori saranno i risultati. Ecco cosa puoi includere per guidare la generazione:

  • Genere: specifica un genere o un mix di generi (ad es. "lo-fi hip hop", "jazz fusion", "cinematic orchestral").
  • Strumenti: indica strumenti specifici (ad es. "pianoforte Fender Rhodes", "chitarra slide", "drum machine TR-808").
  • BPM: imposta il tempo (ad es. "120 BPM", "tempo lento intorno a 70 BPM").
  • Tonalità/Scala: specifica una tonalità musicale (ad es. "in sol maggiore", "in re minore").
  • Stato d'animo e atmosfera: utilizza aggettivi descrittivi (ad es. "nostalgico", "aggressivo", "etereo", "onirico").
  • Struttura: utilizza tag come [Verse], [Chorus], [Bridge], [Intro], [Outro] o timestamp per controllare la progressione del brano.
  • Durata: il modello Clip produce sempre clip di 30 secondi. Per il modello Pro, specifica la durata prevista nel prompt (ad es. "crea una canzone di 2 minuti") o utilizza i timestamp per controllare la durata.

Prompt di esempio

Ecco alcuni esempi di prompt efficaci:

  • "A 30-second lofi hip hop beat with dusty vinyl crackle, mellow Rhodes piano chords, a slow boom-bap drum pattern at 85 BPM, and a jazzy upright bass line. Instrumental only."
  • "An upbeat, feel-good pop song in G major at 120 BPM with bright acoustic guitar strumming, claps, and warm vocal harmonies about a summer road trip."
  • "A dark, atmospheric trap beat at 140 BPM with heavy 808 bass, eerie synth pads, sharp hi-hats, and a haunting vocal sample. In D minor."

Best practice

  • Esegui l'iterazione con Clip. Utilizza il modello lyria-3-clip-preview più veloce per sperimentare con i prompt prima di eseguire una generazione completa con lyria-3-pro-preview.
  • Usa un testo specifico. I prompt vaghi producono risultati generici. Menziona strumenti, BPM, tonalità, stato d'animo e struttura per ottenere il miglior output.
  • Scegli la tua lingua. Prompt nella lingua in cui vuoi che vengano visualizzati i testi.
  • Utilizza i tag di sezione. I tag [Verse], [Chorus] e [Bridge] forniscono al modello una struttura chiara da seguire.
  • Separa il testo dalle istruzioni. Quando fornisci testi personalizzati, separali chiaramente dalle istruzioni per la direzione musicale.

Limitazioni

  • Sicurezza: tutti i prompt vengono controllati dai filtri di sicurezza. I prompt che attivano i filtri verranno bloccati. Sono inclusi i prompt che richiedono voci di artisti specifici o la generazione di testi protetti da copyright.
  • Filigrana: tutto l'audio generato include una filigrana audio SynthID per l'identificazione. Questa filigrana è impercettibile all'orecchio umano e non influisce sull'esperienza di ascolto.
  • Modifica in più passaggi: la generazione di musica è un processo in un solo passaggio. L'editing iterativo o il perfezionamento di un clip generato tramite più prompt non è supportato nella versione attuale di Lyria 3.
  • Durata: il modello Clip genera sempre clip di 30 secondi. Il modello Pro genera brani che durano un paio di minuti; la durata esatta può essere influenzata dal prompt.
  • Determinismo: i risultati possono variare tra le chiamate, anche con lo stesso prompt.

Passaggi successivi