Genera música con Lyria 3

Lyria 3 es la familia de modelos de generación de música de Google, disponible a través de la API de Gemini. Con Lyria 3, puedes generar audio estéreo de 44.1 kHz de alta calidad a partir de instrucciones de texto o imágenes. Estos modelos ofrecen coherencia estructural, incluidas voces, letras sincronizadas y arreglos instrumentales completos.

La familia Lyria 3 incluye dos modelos:

Modelo ID de modelo Ideal para Duración Salida
Lyria 3 Clip lyria-3-clip-preview Clips cortos, bucles y vistas previas 30 segundos MP3
Lyria 3 Pro lyria-3-pro-preview Canciones completas con versos, estribillos y puentes Un par de minutos (se puede controlar con la instrucción) MP3

Ambos modelos se pueden usar con la nueva API de Interactions, admiten entradas multimodales (texto e imágenes) y producen audio estéreo de alta fidelidad de 44.1 kHz.

Genera un clip de música

El modelo Lyria 3 Clip siempre genera un clip de 30 segundos. Para generar un clip, llama al método interactions.create con una instrucción de texto. La respuesta siempre incluye la letra y la estructura de la canción generadas junto con el audio en el esquema 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."
}'

Genera una canción completa

Usa el modelo lyria-3-pro-preview para generar canciones completas que duren un par de minutos. El modelo Pro comprende la estructura musical y puede crear composiciones con versos, estribillos y puentes distintos. Puedes influir en la duración especificándola en la instrucción (p.ej., "crea una canción de 2 minutos") o usando marcas de tiempo para definir la estructura.

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."
}'

Selecciona el formato de salida

De forma predeterminada, los modelos Lyria 3 generan audio en formato MP3. En el caso de Lyria 3 Pro, también puedes solicitar la salida en formato WAV configurando 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"
  }'

Analiza la respuesta

La respuesta de Lyria 3 contiene varios bloques de contenido dentro del esquema steps. Las interacciones muestran una secuencia de pasos, en la que los pasos model_output contienen el contenido generado. Los bloques de contenido de texto contienen la letra generada o una descripción JSON de la estructura de la canción. Los bloques de contenido con tipo audio contienen los datos de audio codificados en 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

Genera música a partir de imágenes

Lyria 3 admite entradas multimodales. Puedes proporcionar hasta 10 imágenes junto con tu instrucción de texto en la lista input, y el modelo compondrá música inspirada en el contenido visual.

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

Proporciona letras personalizadas

Puedes escribir tu propia letra e incluirla en la instrucción. Usa etiquetas de sección como [Verse], [Chorus] y [Bridge] para ayudar al modelo a comprender la estructura de la canción:

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: ..."
  }'

Controla el tiempo y la estructura

Puedes especificar exactamente lo que sucede en momentos específicos de la canción con marcas de tiempo. Esto es útil para controlar cuándo entran los instrumentos, cuándo se entrega la letra y cómo avanza la canción:

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: ..."
  }'

Genera pistas instrumentales

Para la música de fondo, las bandas sonoras de juegos o cualquier caso de uso en el que no se requieran voces, puedes indicarle al modelo que produzca pistas solo instrumentales:

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."
  }'

Genera música en diferentes idiomas

Lyria 3 genera letras en el idioma de tu instrucción. Para generar una canción con letra en francés, escribe la instrucción en francés. El modelo adapta su estilo vocal y pronunciación para que coincidan con el idioma.

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."
  }'

Inteligencia del modelo

Lyria 3 analiza el proceso de tu instrucción en el que el modelo razona a través de la estructura musical (introducción, verso, estribillo, puente, etc.) según tu instrucción. Esto sucede antes de que se genere el audio y garantiza la coherencia estructural y la musicalidad.

Guía de instrucciones

Cuanto más específica sea la instrucción, mejores serán los resultados. Esto es lo que puedes incluir para guiar la generación:

  • Género: Especifica un género o una combinación de géneros (p.ej., "lo-fi hip hop", "jazz fusion", "orquestal cinematográfico").
  • Instrumentos: Nombra instrumentos específicos (p.ej., "piano Fender Rhodes", "guitarra slide", "máquina de batería TR-808").
  • BPM: Establece el tempo (p.ej., "120 BPM", "tempo lento alrededor de 70 BPM").
  • Clave/escala: Especifica una clave musical (p.ej., "en sol mayor", "re menor").
  • Estado de ánimo y atmósfera: Usa adjetivos descriptivos (p.ej., "nostálgico", "agresivo", "etéreo", "soñador").
  • Estructura: Usa etiquetas como [Verse], [Chorus], [Bridge], [Intro], [Outro] o marcas de tiempo para controlar el progreso de la canción.
  • Duración: El modelo Clip siempre produce clips de 30 segundos. En el caso del modelo Pro, especifica la duración deseada en la instrucción (p.ej., "crea una canción de 2 minutos") o usa marcas de tiempo para controlar la duración.

Ejemplos de instrucciones

Estos son algunos ejemplos de instrucciones eficaces:

  • "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."

Prácticas recomendadas

  • Primero, itera con Clip. Usa el modelo lyria-3-clip-preview más rápido para experimentar con instrucciones antes de comprometerte con una generación completa con lyria-3-pro-preview.
  • Sé específico. Las instrucciones vagas producen resultados genéricos. Menciona instrumentos, BPM, clave, estado de ánimo y estructura para obtener el mejor resultado.
  • Haz coincidir tu idioma. Escribe la instrucción en el idioma en el que quieres que esté la letra.
  • Usa etiquetas de sección. Las etiquetas [Verse], [Chorus] y [Bridge] le dan al modelo una estructura clara para seguir.
  • Separa la letra de las instrucciones. Cuando proporciones letras personalizadas, sepáralas claramente de las instrucciones de dirección musical.

Limitaciones

  • Seguridad: Todos los filtros de seguridad verifican todas las instrucciones. Se bloquearán las instrucciones que activen los filtros. Esto incluye las instrucciones que solicitan voces de artistas específicos o la generación de letras protegidas por derechos de autor.
  • Marcas de agua: Todo el audio generado incluye una marca de agua de audio de SynthID para la identificación. Esta marca de agua es imperceptible para el oído humano y no afecta la experiencia de escucha.
  • Edición de varios turnos: La generación de música es un proceso de un solo turno. La edición iterativa o el perfeccionamiento de un clip generado a través de varias instrucciones no se admite en la versión actual de Lyria 3.
  • Longitud: El modelo Clip siempre genera clips de 30 segundos. El modelo Pro genera canciones que duran un par de minutos. La duración exacta se puede influir a través de la instrucción.
  • Determinismo: Los resultados pueden variar entre las llamadas, incluso con la misma instrucción.

¿Qué sigue?