PHP code example of b7s / whisper-php

1. Go to this page and download the library: Download b7s/whisper-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

b7s / whisper-php example snippets


echo (new Whisper)
    ->audio('/path/to/audio.mp3')
    ->toText();



hisperPHP\Whisper;
use WhisperPHP\Config;

// Create service with default configuration (uses 'base' model)
$whisper = new Whisper();

// Simple transcription
$text = $whisper->audio('/path/to/audio.mp3')->toText();
echo $text;

$whisper = new Whisper();

$result = $whisper
    ->audio('/path/to/audio-2.mp3')
    ->fromLanguage('pt')    // Audio language to increase accuracy
    ->toEnglish()           // Translate any language to English
    ->improveDecode(5)      // Improved decoding algorithm (1-10)
    ->filterNonSpeech(0.5)  // Detects speech vs silence/noise (0-1)
    ->detectSpeakers()      // Detects different speakers
    ->context('Add context and technical terms to improve accuracy')
    ->timeout(600)          // Set timeout in seconds (null = unlimited)
    ->onProgress(fn($p) => echo "{$p}%\n") // Real-time progress
    ->run();

echo $result->detectedLanguage();  // Auto‑detects language
print_r($result->segments()); // Array: text, timestamps, speakers

echo $result->toText(); // Pure text
echo $result->toJson(); // or: toJson(true), toCsv, toVtt, toSrt
$result->saveTo('/path/to/output.srt'); // Save directly to file (auto detects format)

$whisper = new Whisper();

// Use a different model (downloads if needed - This may take some time the first time)
$text = $whisper
    ->useModel('small')
    ->audio('/path/to/audio.mp3')
    ->toText();

// Switch to English-only model for better English accuracy
$text = $whisper
    ->useModel('base.en')
    ->audio('/path/to/english-audio.mp3')
    ->toText();

// Use large model for maximum accuracy
$text = $whisper
    ->useModel('large')
    ->audio('/path/to/important-audio.mp3')
    ->toText();

// Check current model
echo $whisper->getCurrentModel(); // 'large'

// Check available (downloaded) models
print_r($whisper->getAvailableModels()); // ['base', 'small', 'base.en', 'large']

// Check if a specific model is downloaded
if (!$whisper->hasModel('medium')) {
    $whisper->downloadModel('medium');
}

$config = new Config(
    model: 'base',
    language: 'auto',
    dataDir: '/custom/path',
    binaryPath: '/path/binary',
    modelPath: '/path/model',
    ffmpegPath: '/path/ffmpeg',
    chunkSize: 10 * 1024 * 1024, // 10 MB
);

$whisper = new Whisper($config);

// Get plain text
$text = $whisper->audio('/path/to/audio.mp3')->toText();

// Get segments with timestamps
$segments = $whisper->audio('/path/to/audio.mp3')->segments();
// [
//     ['start' => '00:00:00.000', 'end' => '00:00:02.500', 'text' => 'Hello world'],
//     ['start' => '00:00:02.500', 'end' => '00:00:05.000', 'text' => 'How are you?'],
// ]

// Spanish audio → English text
$text = $whisper->audio('/path/to/spanish-audio.mp3')
    ->toEnglish()
    ->toText();
// Output: "Hello, how are you?" (even if spoken in Spanish)

// Auto-detect language (default behavior)
$result = $whisper->audio('/path/to/audio.mp3')->run();
echo $result->detectedLanguage(); // 'en', 'pt', 'es', 'fr', etc.
echo $result->toText();

// Or use the shorthand
$language = $whisper->audio('/path/to/audio.mp3')->detectLanguage();

// Specify Portuguese for better accuracy
$text = $whisper->audio('/path/to/portuguese-audio.mp3')
    ->fromLanguage('pt')
    ->toText();

// Specify Spanish
$text = $whisper->audio('/path/to/spanish-audio.mp3')
    ->fromLanguage('es')
    ->toText();

// The detected language will match what you specified
$result = $whisper->audio('/path/to/audio.mp3')
    ->fromLanguage('pt')
    ->run();
echo $result->detectedLanguage(); // 'pt'

// SRT - Standard subtitle format for videos (used by most video players)
$srt = $whisper->audio('/path/to/audio.mp3')->toSrt();

// VTT - Web-based subtitle format (HTML5 video, YouTube)
$vtt = $whisper->audio('/path/to/audio.mp3')->toVtt();

// JSON - Structured data for APIs and web applications
$json = $whisper->audio('/path/to/audio.mp3')->toJson(); // Compact JSON
$json = $whisper->audio('/path/to/audio.mp3')->toJson(true); // Pretty-printed by default

// CSV - Spreadsheet format for data analysis
$csv = $whisper->audio('/path/to/audio.mp3')->toCsv();

// Save directly to file (format auto-detected from extension)
$whisper->audio('/path/to/audio.mp3')->saveTo('/path/to/output.srt');
$whisper->audio('/path/to/audio.mp3')->saveTo('/path/to/output.vtt');

// Use beam search for better accuracy (slower but more accurate)
$text = $whisper->audio('/path/to/audio.mp3')
    ->improveDecode(5) // beam size: 1-10 (higher = better quality, slower)
    ->toText();

// Enable VAD for better speech segmentation
$segments = $whisper->audio('/path/to/audio.mp3')
    ->filterNonSpeech(0.5) // threshold 0.0-1.0 (lower = more sensitive)
    ->segments();

// Guide transcription with domain-specific context
$text = $whisper->audio('/path/to/medical-audio.mp3')
    ->context('Medical terminology: hypertension, cardiovascular, diagnosis, patient')
    ->toText();

// Technical content
$text = $whisper->audio('/path/to/tech-talk.mp3')
    ->context('Technology terms: API, SDK, framework, Kubernetes, microservices')
    ->toText();

// Names and brands
$text = $whisper->audio('/path/to/meeting.mp3')
    ->context('Attendees: João Silva, Maria Santos. Company: Acme Corp')
    ->toText();

// Detect speaker changes in conversations
$segments = $whisper->audio('/path/to/conversation.mp3')
    ->detectSpeakers()
    ->segments();
// [
//     ['start' => '00:00:00.000', 'end' => '00:00:02.500', 'text' => 'Hello', 'speaker' => 0],
//     ['start' => '00:00:02.500', 'end' => '00:00:05.000', 'text' => 'Hi there', 'speaker' => 1],
//     ['start' => '00:00:05.000', 'end' => '00:00:08.000', 'text' => 'How are you?', 'speaker' => 0],
// ]

// Analyze voice tone after transcription
$result = $whisper->audio('/path/to/audio.mp3')
    ->analyzeVoiceTone()
    ->run();

$tone = $result->voiceTone();

// Check if any shouting or soft speaking was detected
if ($tone['has_shouting']) {
    echo "Shouting detected at:\n";
    foreach ($tone['shouting'] as $segment) {
        echo "  [{$segment['start']} - {$segment['end']}] {$segment['text']}\n";
    }
}

if ($tone['has_soft_speaking']) {
    echo "Soft/whisper detected at:\n";
    foreach ($tone['soft'] as $segment) {
        echo "  [{$segment['start']} - {$segment['end']}] {$segment['text']}\n";
    }
}

// Inspect all segments with tone and dB levels
foreach ($tone['segments'] as $segment) {
    echo "{$segment['tone']} ({$segment['db']} dBFS): {$segment['text']}\n";
}

// Adjust sensitivity for shouting and soft speaking detection
$result = $whisper->audio('/path/to/audio.mp3')
    ->analyzeVoiceTone(
        shoutThresholdDb: -8.0,  // Default: -10 dBFS (higher = less sensitive)
        softThresholdDb: -28.0,  // Default: -30 dBFS (higher = more sensitive)
    )
    ->run();

$tone = $result->voiceTone();
// [
//   'has_shouting'      => true,                    // Any shouting segments?
//   'has_soft_speaking' => true,                    // Any soft segments?
//   'shouting' => [                                 // Only shouting segments
//       ['start' => '00:00:05.000', 'end' => '00:00:08.000', 'db' => -6.5, 'text' => '...'],
//   ],
//   'soft' => [                                     // Only soft segments
//       ['start' => '00:00:20.000', 'end' => '00:00:23.000', 'db' => -35.2, 'text' => '...'],
//   ],
//   'segments' => [                                 // All segments with tone annotation
//       ['start' => ..., 'end' => ..., 'db' => -15.3, 'tone' => 'normal', 'text' => '...'],
//       ['start' => ..., 'end' => ..., 'db' => -6.5, 'tone' => 'shouting', 'text' => '...'],
//       ['start' => ..., 'end' => ..., 'db' => -35.2, 'tone' => 'soft', 'text' => '...'],
//   ],
// ]

// Monitor transcription progress
$text = $whisper->audio('/path/to/long-audio.mp3')
    ->onProgress(function (int $percent) {
        echo "Progress: {$percent}%\n";
        // Update progress bar, database, websocket, stream, etc.
    })
    ->toText();

// Set custom timeout (in seconds)
$text = $whisper->audio('/path/to/audio.mp3')
    ->timeout(600)  // 10 minutes
    ->toText();

// Disable timeout (unlimited processing time) - RECOMMENDED for large videos
$text = $whisper->audio('/path/to/very-long-audio.mp3')
    ->timeout(null)  // No timeout - unlimited
    ->toText();

// Video files automatically get 20 minutes timeout by default
$text = $whisper->video('/path/to/video.mp4')
    ->toText();  // 20 minutes timeout (auto-applied)

// Override video timeout to unlimited (recommended for large videos)
$text = $whisper->video('/path/to/long-video.mp4')
    ->timeout(null)  // Unlimited - best for large files
    ->toText();

// Or set a custom timeout
$text = $whisper->video('/path/to/video.mp4')
    ->timeout(3600)  // 1 hour
    ->toText();

// Transcribe video files directly
$text = $whisper->video('/path/to/video.mp4')
    ->toText();

// Or use audio() - it auto-detects video files
$text = $whisper->audio('/path/to/video.mp4')
    ->toText();

// Generate subtitles from video
$whisper->video('/path/to/movie.mp4')
    ->detectSpeakers()
    ->saveTo('subtitles.srt');

// Check if a file is a video
if ($whisper->isVideoFile('/path/to/file.mp4')) {
    echo "This is a video file";
}

// Enable chunking for large files (default: 20MB chunks)
$text = $whisper->audio('/path/to/large-podcast.mp3')
    ->chunk()
    ->toText();

// Custom chunk size (e.g., 10MB)
$text = $whisper->audio('/path/to/huge-file.mp3')
    ->chunk(10 * 1024 * 1024)
    ->toText();

// Chunking is automatically enabled for video files
$text = $whisper->video('/path/to/long-video.mp4')->toText();

// Configure default chunk size globally
$config = new Config(chunkSize: 30 * 1024 * 1024); // 30MB
$whisper = new Whisper($config);

$whisper = new Whisper();

// Quick transcription with base model (default)
$quickText = $whisper->audio('/path/to/meeting.mp3')->toText();

// Switch to small model for better accuracy
$whisper->useModel('small');
$betterText = $whisper->audio('/path/to/important-call.mp3')
    ->fromLanguage('pt')  // Specify language for better accuracy
    ->toText();

// Switch to large model for critical transcription
$whisper->useModel('large');
$criticalText = $whisper->audio('/path/to/legal-deposition.mp3')
    ->improveDecode(8)
    ->fromLanguage('en')
    ->toText();

// Check what models you have
print_r($whisper->getAvailableModels()); // ['base', 'small', 'large']

// Generate accurate subtitles with speaker identification
$whisper->video('/path/to/interview.mp4')
    ->improveDecode(5)           // High quality
    ->filterNonSpeech(0.5)       // Remove silence
    ->detectSpeakers()           // Identify who's talking
    ->saveTo('subtitles.srt');

// Process large video file with unlimited timeout (recommended)
$whisper->video('/path/to/long-movie.mp4')
    ->chunk(50 * 1024 * 1024)    // 50MB chunks
    ->timeout(null)              // Unlimited timeout - best for large files
    ->fromLanguage('en')
    ->saveTo('movie-subtitles.srt');

// High-accuracy medical transcription
$result = $whisper->audio('/path/to/consultation.mp3')
            ->improveDecode(8) // Maximum quality
            ->context('Medical terms: hypertension, diabetes, prescription, diagnosis, patient symptoms')
            ->fromLanguage('en')
            ->run();

// Save in multiple formats
$result->saveTo('consultation.txt');
$result->saveTo('consultation.json');

// Detect language and translate to English
$result = $whisper->audio('/path/to/podcast.mp3')
            ->filterNonSpeech(0.6)
            ->run();

$language = $result->detectedLanguage();
echo "Detected language: {$language}\n";

if ($language !== 'en') {
    // Translate to English
    $english = $whisper->audio('/path/to/podcast.mp3')
        ->toEnglish()
        ->toText();
    echo "English translation: {$english}\n";
}

// Transcribe with progress tracking and custom timeout
$segments = $whisper->audio('/path/to/support-call.mp3')
    ->detectSpeakers()
    ->filterNonSpeech(0.5)
    ->timeout(900)  // 15 minutes for long calls
    ->context('Company: Acme Corp. Agents: John, Sarah. Products: Pro Plan, Enterprise')
    ->onProgress(function($percent) {
        // Update database or send websocket update
        updateJobProgress($jobId, $percent);
    })
    ->segments();

// Analyze conversation
foreach ($segments as $segment) {
    $speaker = $segment['speaker'] === 0 ? 'Agent' : 'Customer';
    echo "[{$speaker}] {$segment['text']}\n";
}

// Process multiple files with different settings
$files = [
    ['path' => 'meeting1.mp3', 'type' => 'meeting'],
    ['path' => 'lecture.mp3', 'type' => 'lecture'],
    ['path' => 'interview.mp4', 'type' => 'video'],
];

foreach ($files as $file) {
    // Auto-detect video files
    $transcription = $whisper->isVideoFile($file['path'])
        ? $whisper->video($file['path'])
        : $whisper->audio($file['path']);

    // Apply settings based on type
    match($file['type']) {
        'meeting' => $transcription
            ->detectSpeakers()
            ->context('Meeting attendees and topics'),
        'lecture' => $transcription
            ->improveDecode(5)
            ->filterNonSpeech(0.6),
        'video' => $transcription
            ->chunk()  // Enable chunking for large videos
            ->detectSpeakers()
            ->improveDecode(5),
    };

    $outputPath = preg_replace('/\.(mp3|mp4|mkv|avi)$/', '.srt', $file['path']);
    $transcription->saveTo($outputPath);
}

$result = $whisper->audio('/path/to/audio.mp3')
    ->withTimestamps()
    ->run();

// Access different formats
$result->toText();            // Plain text
$result->segments();          // Array of segments
$result->detectedLanguage();  // Detected language code
$result->toSrt();             // SRT format string
$result->toVtt();             // VTT format string
$result->toJson();            // JSON format string (compact)
$result->toJson(true);        // JSON format string (pretty-printed)
$result->toCsv();             // CSV format string
$result->voiceTone();         // Voice tone analysis (shouting/soft detection)
$result->saveTo('file.srt');  // Save to file



use WhisperPHP\Logger;

class MyLogger implements Logger
{
    public function info(string $message, array $context = []): void
    {
        // Your implementation
    }

    public function error(string $message, array $context = []): void
    {
        // Your implementation
    }

    public function warning(string $message, array $context = []): void
    {
        // Your implementation
    }
}

$whisper = new Whisper(logger: new MyLogger());
bash
composer 
bash
php ./vendor/bin/whisper-setup
bash
# Use a different model
php ./vendor/bin/whisper-setup --model=small

# Specify language
php ./vendor/bin/whisper-setup --model=large --language=pt

# Custom data directory
php ./vendor/bin/whisper-setup --dir=/custom/path

# Show help
php ./vendor/bin/whisper-setup --help
bash
php ./vendor/bin/whisper-status
bash
# Install default model (base - multilingual with auto-detect)
php ./vendor/bin/whisper-setup

# Install specific model
php ./vendor/bin/whisper-setup --model=small.en
php ./vendor/bin/whisper-setup --model=medium
php ./vendor/bin/whisper-setup --model=large