惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

G
Google Developers Blog
Spread Privacy
Spread Privacy
V
Visual Studio Blog
爱范儿
爱范儿
Apple Machine Learning Research
Apple Machine Learning Research
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
GbyAI
GbyAI
Google DeepMind News
Google DeepMind News
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
V
V2EX
J
Java Code Geeks
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Blog — PlanetScale
Blog — PlanetScale
N
Netflix TechBlog - Medium
B
Blog RSS Feed
博客园 - 【当耐特】
有赞技术团队
有赞技术团队
The Register - Security
The Register - Security
Latest news
Latest news
The Cloudflare Blog
Project Zero
Project Zero
月光博客
月光博客
U
Unit 42
Vercel News
Vercel News
Attack and Defense Labs
Attack and Defense Labs
Know Your Adversary
Know Your Adversary
V
Vulnerabilities – Threatpost
F
Full Disclosure
Schneier on Security
Schneier on Security
Google Online Security Blog
Google Online Security Blog
MyScale Blog
MyScale Blog
L
Lohrmann on Cybersecurity
C
CERT Recently Published Vulnerability Notes
博客园 - 叶小钗
腾讯CDC
博客园 - 三生石上(FineUI控件)
T
The Blog of Author Tim Ferriss
D
Darknet – Hacking Tools, Hacker News & Cyber Security
博客园 - Franky
S
Security Affairs
Hacker News: Ask HN
Hacker News: Ask HN
Security Latest
Security Latest
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
MongoDB | Blog
MongoDB | Blog
D
DataBreaches.Net
SecWiki News
SecWiki News
Recorded Future
Recorded Future
NISL@THU
NISL@THU
Hacker News - Newest:
Hacker News - Newest: "LLM"
Cloudbric
Cloudbric

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Laravel AI SDK: Add Text-to-Speech and Voice to Your App in 20 Minutes
Hafiz · 2026-05-01 · via DEV Community

Originally published at hafiz.dev


Taylor Otwell dropped a one-liner on X yesterday that stopped me mid-scroll:

$audio = Str::of('Hello, Laravel')->toAudio();

Enter fullscreen mode Exit fullscreen mode

That's it. One method call and your string becomes audio. No external SDK wiring, no Guzzle calls, no API response parsing. Just ->toAudio() on a Stringable, the same way you'd call ->upper() or ->slug().

If you've been following the Laravel AI SDK through Part 1 (building a smart assistant) and Part 2 (RAG-powered support bot), you already know how text generation and tool calling work. But there's a whole side of the SDK that most developers haven't touched yet: audio. Text-to-speech generation, voice customization, speech-to-text transcription, queued processing, and testing support are all built in.

Let's build with it.

What You'll Build

By the end of this tutorial, you'll have a Laravel app that can:

  • Convert any text to natural-sounding audio and store it
  • Choose between male, female, or specific voice IDs
  • Coach the AI on how the audio should sound (tone, pace, emotion)
  • Transcribe uploaded audio files back to text (with speaker detection)
  • Queue audio generation for background processing
  • Test everything without hitting a single API

We'll start simple and build up. You don't need any AI experience to follow along.

Setup

If you already have the AI SDK installed from a previous tutorial, skip to the next section. Otherwise:

composer require laravel/ai

php artisan vendor:publish --provider="Laravel\Ai\AiServiceProvider"

php artisan migrate

Enter fullscreen mode Exit fullscreen mode

Add your provider credentials to .env. For audio, you need at least one of these:

OPENAI_API_KEY=your-openai-key
ELEVENLABS_API_KEY=your-elevenlabs-key

Enter fullscreen mode Exit fullscreen mode

OpenAI supports both text-to-speech and speech-to-text. ElevenLabs supports both as well, plus Mistral handles transcription. The full provider matrix from the official docs:

Feature Providers
TTS OpenAI, ElevenLabs
STT OpenAI, ElevenLabs, Mistral

That's it for setup. Let's generate some audio.

Your First Audio Generation

The Audio facade gives you a clean, fluent API:

use Laravel\Ai\Audio;

$audio = Audio::of('Your order has been shipped and will arrive by Thursday.')->generate();

Enter fullscreen mode Exit fullscreen mode

The $audio object holds the raw audio content. You can cast it to a string to get the bytes, or store it directly:

// Store on your default disk
$audio->store();

// Store with a specific path and filename
$audio->storeAs('audio', 'order-confirmation.mp3');

// Store on the public disk
$audio->storePublicly();

Enter fullscreen mode Exit fullscreen mode

Want to serve it directly from a controller? Return it as a response:

Route::get('/audio/preview', function () {
    $audio = Audio::of('Welcome to our support line.')->generate();

    return response((string) $audio)
        ->header('Content-Type', 'audio/mpeg');
});

Enter fullscreen mode Exit fullscreen mode

That's a working audio endpoint in five lines. And if you just need a quick one-liner somewhere in your code, the Stringable integration is even shorter:

use Illuminate\Support\Str;

$audio = Str::of('Hello, Laravel')->toAudio();

Enter fullscreen mode Exit fullscreen mode

This is what Taylor tweeted about. The AI SDK registers toAudio() as a method on the Stringable class, so you can chain it alongside ->replace(), ->trim(), or any other string method. It's the same pattern as ->toEmbeddings() for vector search.

Choosing a Voice

The SDK gives you three ways to control the voice:

// Quick gender selection
$audio = Audio::of('Welcome back!')->female()->generate();
$audio = Audio::of('Your package is ready.')->male()->generate();

// Specific voice by ID or name
$audio = Audio::of('Breaking news: Laravel 14 announced.')
    ->voice('alloy')
    ->generate();

Enter fullscreen mode Exit fullscreen mode

OpenAI offers 11+ voices including alloy, ash, coral, echo, fable, nova, onyx, sage, shimmer, and verse. Each has a distinct character. alloy is neutral and balanced, good for most use cases. nova sounds more expressive and warm. onyx has a deeper, more authoritative tone. I'd suggest generating a short sample with each voice before committing to one for production. The difference is noticeable.

If you're using ElevenLabs, you can pass any voice ID from your account, including custom cloned voices. ElevenLabs generally produces more natural-sounding output than OpenAI for longer narration, but OpenAI is faster and cheaper for short clips. The choice depends on what you're building. Quick notifications? OpenAI. Full blog post narrations or product demos? ElevenLabs is probably worth the extra cost.

Style Instructions

This is where things get interesting. The instructions method lets you coach the AI on how the audio should sound:

$audio = Audio::of('Ahoy! Your treasure has arrived!')
    ->female()
    ->instructions('Speak like a friendly pirate captain')
    ->generate();

$audio = Audio::of('We regret to inform you that your account has been suspended.')
    ->male()
    ->instructions('Professional and empathetic, slow pace')
    ->generate();

Enter fullscreen mode Exit fullscreen mode

Think of instructions as a system prompt for voice. You can control tone, pace, emotion, accent style, and delivery. It won't always nail it perfectly (this depends on the provider), but for most use cases it makes a noticeable difference. Try things like "cheerful and upbeat", "calm and measured", or "urgent, like a news anchor".

Five Practical Use Cases

Before we move on, here are patterns I think are worth building:

1. Blog post audio versions. Generate an audio file when a post is published. Store it alongside the post and embed an HTML5 audio player. Accessibility win, and it keeps readers on the page longer.

// In your Post observer or event listener
$audio = Audio::of($post->plain_text_content)
    ->female()
    ->instructions('Conversational and clear, like a podcast host')
    ->generate();

$audio->storeAs('posts', "post-{$post->id}.mp3");

Enter fullscreen mode Exit fullscreen mode

2. Order confirmation voice messages. E-commerce apps can generate a short audio clip summarizing the order and attach it to the confirmation email or display it on the "thank you" page.

3. In-app notifications with voice. Instead of (or alongside) push notifications, generate a short spoken version. Useful for accessibility or for apps used in environments where reading a screen isn't practical.

4. Interactive voice responses. Build a simple IVR system. Use the AI SDK for TTS on the outbound side and transcription on the inbound side. No Twilio SDK needed for the voice generation part.

5. Language learning tools. Generate pronunciation examples dynamically. Pass different instructions for different accents or speaking speeds.

Speech-to-Text Transcription

The SDK handles the reverse direction too. If you have an audio file, turn it into text:

use Laravel\Ai\Transcription;

// From a file on disk
$text = Transcription::fromStorage('recordings/meeting.mp3')->generate();

echo (string) $text; // "Alright team, let's review the Q2 numbers..."

Enter fullscreen mode Exit fullscreen mode

You can also transcribe from a raw file path:

$text = Transcription::fromPath('/tmp/uploaded-audio.webm', 'audio/webm')->generate();

Enter fullscreen mode Exit fullscreen mode

This pairs naturally with file uploads. A typical controller might look like this:

public function transcribe(Request $request)
{
    $request->validate([
        'audio' => 'required|file|mimes:mp3,wav,webm',
    ]);

    $path = $request->file('audio')->store('temp');

    $text = Transcription::fromPath(
        Storage::path($path),
        $request->file('audio')->getMimeType()
    )->generate();

    Storage::delete($path);

    return response()->json(['text' => (string) $text]);
}

Enter fullscreen mode Exit fullscreen mode

That's a complete speech-to-text endpoint. Twenty lines, including validation and cleanup. Compare that to wiring up the OpenAI API manually with Guzzle, handling multipart uploads, parsing JSON responses, and managing error states. The SDK handles all of that behind a single generate() call.

One thing to watch for: the transcription providers have file size limits. OpenAI's Whisper accepts files up to 25MB. For longer recordings, you'll need to split the audio into chunks first. FFmpeg handles this well, and you can use Laravel's Process facade to run it:

use Illuminate\Support\Facades\Process;

Process::run("ffmpeg -i input.mp3 -f segment -segment_time 300 -c copy chunk_%03d.mp3");

Enter fullscreen mode Exit fullscreen mode

That splits a recording into 5-minute chunks. Transcribe each one and concatenate the results.

Speaker Diarization

For meeting recordings or multi-speaker audio, the SDK supports speaker diarization, which identifies who spoke when. This is useful for automated meeting notes, call center analytics, or podcast transcription workflows.

Not all providers handle diarization the same way. OpenAI's newer GPT-4o Transcribe model supports it natively, but the legacy Whisper model does not. ElevenLabs supports it as well. Check the official AI SDK documentation for the exact method chain and provider requirements, as this feature is still evolving across providers.

Queued Audio Generation

Audio generation takes time, especially for longer text. You don't want users staring at a spinner while their blog post gets narrated. Queue it:

Audio::of($post->plain_text_content)
    ->female()
    ->instructions('Conversational, like a podcast')
    ->generateQueued();

Enter fullscreen mode Exit fullscreen mode

The SDK dispatches a job to your queue system. If you need to do something with the audio after it generates (store it, notify the user), chain a callback:

Audio::of($post->plain_text_content)
    ->female()
    ->generateQueued()
    ->then(function ($audio) use ($post) {
        $audio->storeAs('posts', "post-{$post->id}.mp3");

        $post->update(['has_audio' => true]);
    });

Enter fullscreen mode Exit fullscreen mode

This is the pattern I'd use for blog post narration. Publish the post, dispatch the audio job, and update the post record when the file is ready. The reader sees the audio player appear once it's processed.

Switching Providers

By default, the SDK uses whatever provider you've configured in config/ai.php. But you can switch providers per request:

use Laravel\Ai\Enums\Lab;

// Use ElevenLabs for higher-quality voice
$audio = Audio::of('Premium audio content')
    ->generate(Lab::ElevenLabs);

// Use OpenAI for faster, cheaper generation
$audio = Audio::of('Quick notification')
    ->generate(Lab::OpenAI);

Enter fullscreen mode Exit fullscreen mode

If you've read the AI SDK overview, you'll recognize this pattern. It's the same Lab enum used for text generation. One SDK, one API, multiple providers.

Testing Without API Calls

You don't want your test suite hitting OpenAI's API every time it runs. The SDK has built-in fakes:

use Laravel\Ai\Audio;
use Laravel\Ai\Transcription;

it('generates audio for a new post', function () {
    Audio::fake();

    $post = Post::factory()->create();

    // Your code that generates audio...

    Audio::assertGenerated(function ($audio) {
        return str_contains($audio->text, 'order has been shipped');
    });
});

it('transcribes uploaded audio', function () {
    Transcription::fake();

    // Your code that transcribes...

    Transcription::assertGenerated();
});

Enter fullscreen mode Exit fullscreen mode

Audio::fake() prevents any HTTP requests and lets you assert that generation happened with the right inputs. Same pattern as Http::fake(), Mail::fake(), or Queue::fake(). If you've tested anything in Laravel before, this is familiar.

Production Considerations

A few things I'd think about before shipping audio features to real users.

Cache aggressively. If the same text generates the same audio, store the result and serve it from disk next time. Don't regenerate audio for content that hasn't changed. For blog posts, generate once on publish and serve the stored file forever. Invalidate only when the content is updated.

Handle failures gracefully. API calls fail. Rate limits hit. Provider outages happen. Wrap your audio generation in try/catch blocks and make sure the user experience degrades gracefully when audio isn't available. A missing audio player is better than a 500 error.

try {
    $audio = Audio::of($text)->generate();
    $audio->storeAs('audio', "post-{$id}.mp3");
} catch (\Throwable $e) {
    Log::warning("Audio generation failed for post {$id}", [
        'error' => $e->getMessage(),
    ]);
    // Continue without audio - the post still works
}

Enter fullscreen mode Exit fullscreen mode

Set appropriate timeouts. Longer text takes longer to generate. If you're narrating a 2,000-word blog post, the API might need 15-20 seconds. That's too long for a synchronous request. Use queued generation for anything over a paragraph or two.

Monitor your spending. Both OpenAI and ElevenLabs charge per character. If you have a webhook or background job that generates audio, a bug could run up a surprising bill fast. Set up billing alerts on your provider accounts and consider adding a character count guard in your code.

Costs and Rate Limits

A quick note on pricing, because this comes up every time someone talks about AI in production. As of right now, OpenAI's TTS costs roughly $15 per million characters. For context, a 2,000-word blog post is about 10,000 characters. That's $0.15 per post narrated. ElevenLabs offers 10,000 characters per month on their free tier, with paid plans starting around $5/month for higher quotas and premium voices.

For transcription, OpenAI Whisper costs about $0.006 per minute of audio. A 30-minute meeting transcript runs roughly $0.18.

These costs are low enough for most production use cases, but cache or store your generated audio. Don't regenerate the same content repeatedly.

FAQ

Can I use this without the AI SDK's agent features?

Yes. The Audio and Transcription facades are completely standalone. You don't need to create agents, define tools, or set up conversations. Just composer require laravel/ai, add your API key, and call Audio::of('text')->generate().

Which providers support the ->toAudio() Stringable method?

The ->toAudio() method uses whatever default provider you've configured for audio in config/ai.php. You can set this to OpenAI or ElevenLabs. The Stringable shortcut doesn't accept provider arguments directly, so configure your preferred provider in the config file.

Does this work with Laravel 12 or only Laravel 13?

The AI SDK works with both Laravel 12 and 13. The ->toAudio() Stringable integration, the Audio facade, and the Transcription class are available in the current stable version of the SDK regardless of which Laravel version you're running.

Can I generate audio in languages other than English?

Yes. Pass your text in any language the provider supports. OpenAI's TTS handles dozens of languages automatically based on the input text. For ElevenLabs, you may need to select a voice trained for your target language, or use their multilingual model.

How long can the input text be?

OpenAI's TTS endpoint accepts up to 4,096 characters per request. For longer content (like a full blog post), you'll need to split the text into chunks and generate separate audio files. Concatenation is straightforward with FFmpeg.

What's Next

Text generation, tool calling, RAG, and now audio. The AI SDK covers a lot of ground from a single composer require. If you haven't tried the text features yet, start with Part 1 and Part 2. If you're already using the SDK and want to explore what Claude Opus 4.7 changes for your AI setup, that post covers the breaking changes and token adjustments you need to know about.

If you're building voice features into a Laravel app and need help with architecture, queue strategies, or production scaling, get in touch.