PHP code example of samandar / laravel-elevenlabs

1. Go to this page and download the library: Download samandar/laravel-elevenlabs 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/ */

    

samandar / laravel-elevenlabs example snippets


use Samandar\LaravelElevenLabs\Facades\ElevenLabs;

// Text-to-Speech
$result = ElevenLabs::audio()->textToSpeech('Hello, world!');

// Speech-to-Text
$uploadedFile = request()->file('audio');
$result = ElevenLabs::audio()->speechToText($uploadedFile);

// Speech-to-Speech conversion
$result = ElevenLabs::audio()->speechToSpeech(
    'voice_id_here',
    $uploadedFile
);

// Streaming TTS
$stream = ElevenLabs::audio()->streamTextToSpeech('Hello streaming!');
foreach ($stream as $chunk) {
    // Process audio chunk
    echo $chunk;
}

// Save audio to file
$saved = ElevenLabs::audio()->saveAudioToFile(
    $audioContent,
    storage_path('app/speech.mp3')
);

// Text-to-Speech with file saving
$result = ElevenLabs::audio()->textToSpeechAndSave(
    'Hello, this will be saved!',
    storage_path('app/test-speech.mp3')
);

// 🆕 NEW: Audio Isolation (experimental)
// Note: This method is experimental and may change as ElevenLabs finalizes the endpoint.
$isolatedAudio = ElevenLabs::audio()->audioIsolation($uploadedFile);

// 🆕 NEW: Sound Generation - Create sound effects from text
$soundEffect = ElevenLabs::audio()->soundGeneration(
    'Thunder and rain sounds',  // Text description
    10,                         // Duration in seconds (optional)
    'strong'                    // Prompt influence or guidance (optional)
);

// Get available voices
$voices = ElevenLabs::voice()->getVoices();

// Get specific voice details
$voice = ElevenLabs::voice()->getVoice('voice_id_here');

// Add custom voice
$result = ElevenLabs::voice()->addVoice(
    'My Custom Voice',
    $audioFiles, // Array of UploadedFile objects
    'Description of the voice'
);

// Edit voice settings
$result = ElevenLabs::voice()->editVoiceSettings('voice_id', [
    'stability' => 0.7,
    'similarity_boost' => 0.8
]);

// Delete voice
$result = ElevenLabs::voice()->deleteVoice('voice_id');

// Get shared voices from community
$sharedVoices = ElevenLabs::voice()->getSharedVoices();

// Pronunciation dictionaries
$dictionaries = ElevenLabs::voice()->getPronunciationDictionaries();
$result = ElevenLabs::voice()->addPronunciationDictionary(
    'My Dictionary',
    [['string' => 'word', 'phoneme' => 'pronunciation']]
);

// 🆕 NEW: Create voice previews
$result = ElevenLabs::voice()->createVoicePreviews(
    'Hello, this is a voice preview test',
    'voice_id_here'
);
);

// Conversational AI settings
$settings = ElevenLabs::ai()->getConversationalAISettings();
$result = ElevenLabs::ai()->updateConversationalAISettings($newSettings);

// Knowledge base management
$result = ElevenLabs::ai()->createKnowledgeBaseFromURL('https://docs.example.com');
$knowledgeBases = ElevenLabs::ai()->getKnowledgeBases();
$result = ElevenLabs::ai()->deleteKnowledgeBase('kb_id');

// Knowledge base documents (file upload)
$multipart = [
    [
        'name' => 'file',
        'contents' => fopen(storage_path('app/docs.pdf'), 'r'),
        'filename' => 'docs.pdf'
    ]
];
$doc = ElevenLabs::ai()->createKnowledgeBaseDocumentFromFile($multipart);
$docContent = ElevenLabs::ai()->getKnowledgeBaseDocumentContent('document_id');

// RAG Index overview
$rag = ElevenLabs::ai()->getRagIndexOverview();

// Workspace secrets
$secrets = ElevenLabs::ai()->getWorkspaceSecrets();

// 🆕 NEW: Signed URL and Widget
$signed = ElevenLabs::ai()->getSignedUrl('agent_id_here');
$widget = ElevenLabs::ai()->getAgentWidgetConfig('agent_id_here');

// 🆕 NEW: Tools and MCP Servers
$tools = ElevenLabs::ai()->listTools();
$tool = ElevenLabs::ai()->getTool('tool_id');
$createdTool = ElevenLabs::ai()->createTool(['name' => 'Search Tool']);
$dependentAgents = ElevenLabs::ai()->getDependentAgents('tool_id');

$mcpServers = ElevenLabs::ai()->listMcpServers();
$createdMcp = ElevenLabs::ai()->createMcpServer(['name' => 'Internal MCP']);
$approval = ElevenLabs::ai()->createMcpApprovalPolicy(['policy' => 'allow_all']);

// Dashboard settings
$dashboard = ElevenLabs::ai()->getDashboardSettings();

// 🆕 NEW: AI Agents Management
// List all conversational AI agents with pagination
$agents = ElevenLabs::ai()->getAgents('cursor_here', 10);

// Create a new AI agent
$agentData = [
    'name' => 'Customer Support Agent',
    'prompt' => 'You are a helpful customer support assistant.',
    'voice_id' => '21m00Tcm4TlvDq8ikWAM',
    'language' => 'en'
];
$newAgent = ElevenLabs::ai()->createAgent($agentData);

// 🆕 NEW: Conversations Management
// List conversations with pagination and filters
$conversations = ElevenLabs::ai()->getConversations(
    'cursor_here',
    10 // page size
);

// Get specific conversation details
$conversation = ElevenLabs::ai()->getConversation('conversation_id');

// Get conversation audio file
$audio = ElevenLabs::ai()->getConversationAudio('conversation_id');

// 🆕 NEW: Batch Calling
// Submit a batch calling job
$callsData = [
    [
        'phone_number' => '+1234567890',
        'message' => 'Hello, this is a test call.'
    ],
    [
        'phone_number' => '+0987654321', 
        'message' => 'Another test message.'
    ]
];
$batchJob = ElevenLabs::ai()->submitBatchCalling($callsData);

// Get batch calling status
$status = ElevenLabs::ai()->getBatchCalling('batch_id');

// Studio projects
$projects = ElevenLabs::studio()->getStudioProjects();
$project = ElevenLabs::studio()->getStudioProject('project_id');

// Chapters and snapshots
$chapter = ElevenLabs::studio()->getChapter('project_id', 'chapter_id');
$chapterSnaps = ElevenLabs::studio()->listChapterSnapshots('project_id', 'chapter_id');
$chapterSnapshot = ElevenLabs::studio()->getChapterSnapshot('project_id', 'chapter_id', 'snapshot_id');
$projectSnapshot = ElevenLabs::studio()->getProjectSnapshot('project_id', 'project_snapshot_id');

// Create project from file
$result = ElevenLabs::studio()->createStudioProject(
    $uploadedFile,
    'My Project Name'
);

// Convert project
$result = ElevenLabs::studio()->convertStudioProject('project_id');

// Delete project
$result = ElevenLabs::studio()->deleteStudioProject('project_id');

// Dubbing operations
$result = ElevenLabs::studio()->createDubbing(
    $sourceFile,
    'spanish', // target language
    'english', // source language (optional)
    2 // number of speakers (optional)
);

$dubbing = ElevenLabs::studio()->getDubbing('dubbing_id');
$audio = ElevenLabs::studio()->getDubbedAudio('dubbing_id', 'es');

// Podcast projects
$result = ElevenLabs::studio()->createPodcastProject($podcastData);

// Dubbing transcript (SRT/WEBVTT)
$transcript = ElevenLabs::studio()->getDubbingTranscript('dubbing_id', 'srt');

// User information and usage
$userInfo = ElevenLabs::analytics()->getUserInfo();
$usage = ElevenLabs::analytics()->getCharacterUsage();
$models = ElevenLabs::analytics()->getModels();

// Generation history
$history = ElevenLabs::analytics()->getHistory();
$historyItem = ElevenLabs::analytics()->getHistoryItem('history_id');
$result = ElevenLabs::analytics()->deleteHistoryItem('history_id');

// Download multiple history items
$result = ElevenLabs::analytics()->downloadHistory(['id1', 'id2']);

// 🆕 NEW: Get user subscription info
$subscription = ElevenLabs::analytics()->getUserSubscription();

// Share workspace resources
$result = ElevenLabs::workspace()->shareWorkspaceResource(
    'resource_id',
    $shareData
);

// Get resources and a specific resource
$resources = ElevenLabs::workspace()->getWorkspaceResources();
$resource = ElevenLabs::workspace()->getWorkspaceResource('resource_id');

// Search groups
$groups = ElevenLabs::workspace()->searchWorkspaceGroups(['q' => 'team']);

// Members
$members = ElevenLabs::workspace()->getWorkspaceMembers();
$invitation = ElevenLabs::workspace()->inviteWorkspaceMember('[email protected]', ['read']);
$removed = ElevenLabs::workspace()->removeWorkspaceMember('member_id');

// Workspace-level secrets (optional)
$workspaceSecrets = ElevenLabs::workspace()->getWorkspaceSecrets();

use Samandar\LaravelElevenLabs\Facades\ElevenLabs;

// Basic text-to-speech conversion
$result = ElevenLabs::textToSpeech('Hello, world!');

if ($result['success']) {
    // Save audio to file
    $saved = ElevenLabs::saveAudioToFile(
        $result['audio'], 
        storage_path('app/speech.mp3')
    );
}

// Convert text to speech and save in one step
$result = ElevenLabs::textToSpeechAndSave(
    'Hello, this is a test message!',
    storage_path('app/test-speech.mp3')
);

// Get available voices
$voices = ElevenLabs::getVoices();
if ($voices['success']) {
    foreach ($voices['voices'] as $voice) {
        echo $voice['name'] . ' - ' . $voice['voice_id'] . "\n";
    }
}

// Use custom voice settings
$result = ElevenLabs::textToSpeech(
    'Custom voice settings example',
    '21m00Tcm4TlvDq8ikWAM', // Voice ID
    [
        'stability' => 0.7,
        'similarity_boost' => 0.8,
        'style' => 0.6,
        'use_speaker_boost' => true
    ]
);

use Samandar\LaravelElevenLabs\Services\ElevenLabsService;

class SpeechController extends Controller
{
    public function generateSpeech(ElevenLabsService $elevenLabs)
    {
        $result = $elevenLabs->textToSpeech('Hello from controller!');
        
        if ($result['success']) {
            return response($result['audio'], 200)
                ->header('Content-Type', $result['content_type']);
        }
        
        return response()->json(['error' => $result['error']], 500);
    }
}



namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Samandar\LaravelElevenLabs\Facades\ElevenLabs;

class TextToSpeechController extends Controller
{
    public function convert(Request $request)
    {
        $request->validate([
            'text' => 'e($result['audio'], 200)
                ->header('Content-Type', $result['content_type'])
                ->header('Content-Disposition', 'attachment; filename="speech.mp3"');
        }

        return response()->json([
            'error' => 'Failed to generate speech',
            'message' => $result['error']
        ], 500);
    }

    public function getVoices()
    {
        $result = ElevenLabs::getVoices();
        
        if ($result['success']) {
            return response()->json($result['voices']);
        }

        return response()->json([
            'error' => 'Failed to fetch voices',
            'message' => $result['error']
        ], 500);
    }
}

[
    'success' => true,
    'audio' => '...', // Binary audio data (for TTS methods)
    'content_type' => 'audio/mpeg',
    // ... other relevant data
]

[
    'success' => false,
    'error' => 'Error message',
    'code' => 400
]

$voiceSettings = [
    'stability' => 0.5,        // 0.0 to 1.0
    'similarity_boost' => 0.5, // 0.0 to 1.0
    'style' => 0.5,           // 0.0 to 1.0
    'use_speaker_boost' => true
];

$result = ElevenLabs::textToSpeech('Hello!', 'voice_id', $voiceSettings);

return [
    'api_key' => env('ELEVENLABS_API_KEY'),
    'default_voice_id' => env('ELEVENLABS_DEFAULT_VOICE_ID', '21m00Tcm4TlvDq8ikWAM'),
    'default_model' => env('ELEVENLABS_DEFAULT_MODEL', 'eleven_multilingual_v2'),
    'audio_storage_path' => env('ELEVENLABS_AUDIO_PATH', 'elevenlabs/audio'),
    'timeout' => env('ELEVENLABS_TIMEOUT', 30),
    'log_requests' => env('ELEVENLABS_LOG_REQUESTS', false),
    'default_voice_settings' => [
        'stability' => 0.5,
        'similarity_boost' => 0.5,
        'style' => 0.5,
        'use_speaker_boost' => true,
    ],
];

$result = ElevenLabs::textToSpeech('Hello!');

if (!$result['success']) {
    Log::error('ElevenLabs error: ' . $result['error']);
    // Handle error appropriately
}
bash
php artisan vendor:publish --tag=elevenlabs-config