Audio and Video Generation

Updated · 10 min read
hardPython 3.13aigenerative-aiaudio-generationvideo-generationdeepfakesprovenance

Audio and video generation uses the same ideas as text and image generation, applied to sound and moving pictures. Speech generation (text-to-speech and voice cloning) turns text into a voice; music and sound generation creates songs and effects from a description; video generation creates a sequence of frames from a prompt or an image. These tools are powerful for education, accessibility and creative work, and they also make deepfakes: convincing fake recordings of real people.

What Can Be Generated

KindDescription
Text-to-speechIt is used to read text aloud in a natural voice
Voice cloningIt is used to copy a real person's voice from a short sample; it must have that person's consent
Music and sound effectsIt is used to create songs, background music or sounds from a text description
Text-to-videoIt is used to create short clips from a prompt, often with diffusion over many frames at once
Image-to-videoIt is used to animate a still image
Lip sync and dubbingIt is used to change what a person in a video appears to say, for example to translate it

Example: The Same Text, Different Speech

The programs in this chapter need pip install torch transformers diffusers scikit-learn scipy pillow. The first run of each pretrained model downloads it from Hugging Face; download and loading messages are left out of the output shown.

This program uses MMS-TTS from "Speech Recognition and Speech Synthesis" to say one announcement three ways.

Generated media: variable, frame by frame, and easy to strip of its label
Python
import numpy as np
import torch
from scipy.io import wavfile
from transformers import AutoTokenizer, VitsModel
 
# MMS-TTS from "Speech Recognition and Speech Synthesis" (license CC BY-NC 4.0)
tokenizer = AutoTokenizer.from_pretrained("facebook/mms-tts-eng")
model = VitsModel.from_pretrained("facebook/mms-tts-eng")
text = "Welcome to the spring concert. Please find your seats."
inputs = tokenizer(text, return_tensors="pt")
rate = model.config.sampling_rate
 
def speak(seed, speed=1.0):
    torch.manual_seed(seed)
    model.speaking_rate = speed                        # above 1 is faster
    with torch.no_grad():
        return model(**inputs).waveform[0].numpy()
 
for seed, speed in [(0, 1.0), (1, 1.0), (0, 1.3)]:
    audio = speak(seed, speed)
    name = f"concert_seed{seed}_speed{speed}.wav"
    wavfile.write(name, rate, (audio / np.abs(audio).max() * 32767).astype(np.int16))
    print(f"seed {seed}, speed {speed}: {len(audio) / rate:.2f} seconds -> {name}")
 
a, b = speak(0), speak(1)
n = min(len(a), len(b))
print("\nSame text, two seeds: correlation of the waveforms", round(float(np.corrcoef(a[:n], b[:n])[0, 1]), 3))
Output
seed 0, speed 1.0: 4.13 seconds -> concert_seed0_speed1.0.wav
seed 1, speed 1.0: 3.79 seconds -> concert_seed1_speed1.0.wav
seed 0, speed 1.3: 3.49 seconds -> concert_seed0_speed1.3.wav
 
Same text, two seeds: correlation of the waveforms 0.012

Explanation:

  • The same text with different seeds gives different speech: 4.13 seconds with seed 0 and 3.79 with seed 1. The model chooses the timing of each sound with some randomness, as a person never says a sentence the same way twice.
  • A correlation of 0.012 means the two waveforms are almost unrelated sample by sample, even though they say the same words.
  • speaking_rate = 1.3 makes the same voice faster: 3.49 seconds. Generators expose controls like speed, pitch, style and emotion.

Example: Video Is Many Frames That Must Agree

A video is a sequence of images, and the hard part of generating one is keeping every frame consistent with the one before. This program uses the tiny digit diffusion model from "Diffusion Models" to make two 12-frame animations of a 2.

Python
import math
 
import torch
from PIL import Image
from sklearn.datasets import load_digits
from torch import nn
 
digits = load_digits()
X = torch.tensor(digits.data / 8 - 1, dtype=torch.float32)     # 1,797 digits, 64 pixels from -1 to 1
labels = torch.tensor(digits.target)
 
T = 100
betas = torch.linspace(0.0001, 0.1, T)
alphas = 1 - betas
alpha_bar = torch.cumprod(alphas, dim=0)
 
class Denoiser(nn.Module):
    def __init__(self):
        super().__init__()
        self.step = nn.Embedding(T, 64)
        self.digit = nn.Embedding(10, 64)          # the "prompt": which digit to draw
        self.net = nn.Sequential(nn.Linear(64 + 64, 256), nn.SiLU(), nn.Linear(256, 256), nn.SiLU(), nn.Linear(256, 64))
 
    def forward(self, x, t, d):
        return self.net(torch.cat([x, self.step(t) + self.digit(d)], dim=1))
 
torch.manual_seed(0)
model = Denoiser()
optimizer = torch.optim.Adam(model.parameters(), lr=0.002)
 
# Train the same denoiser as in "Diffusion Models" (about 6 seconds)
for step in range(1, 6001):
    i = torch.randint(0, len(X), (128,))
    t = torch.randint(0, T, (128,))
    noise = torch.randn(128, 64)
    a = alpha_bar[t].sqrt()[:, None]
    noisy = a * X[i] + (1 - alpha_bar[t]).sqrt()[:, None] * noise
    loss = nn.functional.mse_loss(model(noisy, t, labels[i]), noise)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
 
@torch.no_grad()
def generate(digit, start):
    g = torch.Generator().manual_seed(99)              # the same small noise at every step, for every frame
    x = start.clone()
    for t in reversed(range(T)):
        predicted = model(x, torch.tensor([t]), torch.tensor([digit]))
        x = (x - betas[t] / (1 - alpha_bar[t]).sqrt() * predicted) / alphas[t].sqrt()
        if t > 0:
            x = x + betas[t].sqrt() * torch.randn(1, 64, generator=g)
    return x.clamp(-1, 1).reshape(8, 8)
 
def video(frames, name):
    images = [Image.fromarray(((f.numpy() + 1) * 127.5).astype("uint8")).resize((64, 64), Image.NEAREST) for f in frames]
    images[0].save(name, save_all=True, append_images=images[1:], duration=150, loop=0)
    change = sum((a - b).abs().mean().item() for a, b in zip(frames, frames[1:])) / (len(frames) - 1)
    print(f"{name}: {len(frames)} frames, average change between frames {change:.3f}")
 
z0 = torch.randn(1, 64, generator=torch.Generator().manual_seed(0))
z1 = torch.randn(1, 64, generator=torch.Generator().manual_seed(1))
 
# 1. Every frame generated on its own, from unrelated noise: it flickers
independent = [generate(2, torch.randn(1, 64, generator=torch.Generator().manual_seed(10 + k))) for k in range(12)]
video(independent, "flicker.gif")
 
# 2. Each frame starts from noise that moves only a little from the frame before: smooth
smooth = [generate(2, math.cos(k * 0.05) * z0 + math.sin(k * 0.05) * z1) for k in range(12)]
video(smooth, "smooth.gif")
Output
flicker.gif: 12 frames, average change between frames 0.053
smooth.gif: 12 frames, average change between frames 0.003

Explanation:

  • flicker.gif makes every frame on its own, from unrelated starting noise. Each frame is a fine 2, but they don't match, so the animation flickers: an average change of 0.053 between frames.
  • smooth.gif starts each frame from noise that has moved only a little from the previous frame's, so neighboring frames come out almost the same: an average change of 0.003, about 18 times smaller.
  • Real video models solve this by generating many frames together, with attention across time as well as across the image, so objects keep their shape, color and position. It is also why video generation needs far more computing power than images.

A deepfake is generated or altered media that shows a real person saying or doing something they didn't. Deepfakes have been used for fraud (a cloned voice of a family member asking for money), harassment, election misinformation and fake endorsements.

DefenseWhat it does
ConsentOnly clone or depict a real person's voice or face with their clear permission
Content credentials (C2PA)A standard for signed records attached to a file, saying how it was made and edited
WatermarksHidden signals inside generated images, audio or text that a detector can find, such as Google's SynthID
LabelsPlatforms and some laws require AI-generated media to be disclosed; the EU AI Act requires deepfakes to be labeled
Checking sourcesVerify surprising media through a second, trusted channel before acting on it

Example: Why Labels in Files Are Fragile

This program labels a generated image as AI-made, then does what a screenshot, upload or format change often does.

Python
import hashlib
 
from PIL import Image
from PIL.PngImagePlugin import PngInfo
 
image = Image.open("apple_steps25.png")                 # made by the diffusion checkpoint
 
# 1. Label the file: a provenance note stored inside the PNG
info = PngInfo()
info.add_text("ai_generated", "true")
info.add_text("generator", "nota-ai/bk-sdm-tiny, 25 steps, seed 0")
image.save("apple_labeled.png", pnginfo=info)
print("Label read back:", Image.open("apple_labeled.png").text)
 
# 2. A fingerprint of the exact file
def fingerprint(path):
    return hashlib.sha256(open(path, "rb").read()).hexdigest()[:16]
print("SHA-256 of the labeled file:", fingerprint("apple_labeled.png"))
 
# 3. What a screenshot, upload or format change does
Image.open("apple_labeled.png").convert("RGB").save("apple_copy.jpg", quality=90)
print("\nAfter saving as JPEG:")
print("  Label:", Image.open("apple_copy.jpg").info.get("ai_generated", "gone"))
print("  SHA-256:", fingerprint("apple_copy.jpg"), "(no longer matches)")
Output
Label read back: {'ai_generated': 'true', 'generator': 'nota-ai/bk-sdm-tiny, 25 steps, seed 0'}
SHA-256 of the labeled file: 5e882fba8755caf9
 
After saving as JPEG:
  Label: gone
  SHA-256: 343ed5bfa25d17be (no longer matches)

Explanation:

  • The label is stored inside the PNG file as text fields, and reads back correctly.
  • A SHA-256 fingerprint identifies the exact file; any change to the file changes it.
  • Saving the same picture as a JPEG removes the label and changes the fingerprint. Many apps and social networks re-save uploaded images, so simple labels often disappear.
  • This is why provenance uses several layers: signed content credentials that show when a file has been changed, watermarks inside the pixels or sound that survive re-saving better, and platform labels. None is perfect, so checking the source still matters.

Common Mistakes

Assuming a missing label means the media is real. Labels are easy to remove; absence proves nothing.

Trusting detectors completely. AI-media detectors make mistakes in both directions; use them as one signal.

Using a voice or face without permission. Even for a joke or a class project, get consent.

Forgetting licenses. Voice, music and video models often limit commercial use; MMS-TTS here is non-commercial only.

Interview Corner

Why is video generation harder than image generation?

A video must be consistent across many frames: objects must keep their identity, shape and motion over time. Models generate frames jointly with attention across time, which needs much more data and compute than single images.

How can people tell whether media is AI-generated?

No single method is reliable. Content credentials record how a file was made, watermarks embed a detectable signal, platforms add labels, and people should verify surprising media through a trusted source. Metadata labels alone are easily stripped.

Practice

Exercise: a wider move. In the video program, change k * 0.05 to k * 0.2 in the smooth animation. How does the average change between frames compare now, and what does the GIF look like?

Check your understanding:

  1. Why did the same sentence take 4.13 seconds with one seed and 3.79 with another?
  2. Why did the independently generated frames flicker?
  3. Why did the "ai_generated" label disappear?

Quick check: audio and video generation

4 questions
1What happened to the speech with a different seed?
2Which animation had the smaller change between frames?
3What happened to the label after saving as JPEG?
4What should you do before cloning someone's voice?

Key Takeaways

Quick reference

NeedCode or practice
Change speaking speedmodel.speaking_rate = 1.3
Save an animated GIFframes[0].save(name, save_all=True, append_images=frames[1:], duration=150, loop=0)
Add a PNG text labelPngInfo().add_text("ai_generated", "true")
Fingerprint a filehashlib.sha256(open(path, "rb").read()).hexdigest()
Verify suspicious mediaCall back on a known number; check the original source

Was this tutorial helpful?

Lesson 157 of 186