### Install Dependencies with Composer Source: https://github.com/yoanbernabeu/music-gpt-bundle/blob/main/CONTRIBUTING.md Installs project dependencies using Composer. This command reads the composer.json file to download and set up all required libraries for the project. ```bash composer install ``` -------------------------------- ### Install Music GPT Bundle Source: https://context7.com/yoanbernabeu/music-gpt-bundle/llms.txt Instructions for installing the Music GPT Bundle using Composer and configuring API authentication via environment variables. It also shows manual bundle registration if Symfony Flex is not used. ```bash # Install via Composer composer require yoanbernabeu/music-gpt-bundle # The bundle auto-registers with Symfony Flex # Manual registration in config/bundles.php if needed: # YoanBernabeu\MusicGptBundle\MusicGptBundle::class => ['all' => true] ``` ```yaml # config/packages/music_gpt.yaml music_gpt: api: api_key: '%env(MUSIC_GPT_API_KEY)%' ``` ```bash # .env file MUSIC_GPT_API_KEY=your_api_key_from_musicgpt_com ``` -------------------------------- ### Complete Music Generation Workflow Example (PHP) Source: https://github.com/yoanbernabeu/music-gpt-bundle/blob/main/README.md Demonstrates a full workflow for generating music using the Music GPT Bundle. It includes steps for initiating music generation, polling for completion, and handling success or failure states. This example requires the MusicAIServiceInterface and ConversionServiceInterface. ```php use YoanBernabeu\MusicGptBundle\Contract\MusicAIServiceInterface; use YoanBernabeu\MusicGptBundle\Contract\ConversionServiceInterface; use YoanBernabeu\MusicGptBundle\DTO\MusicAI\MusicAIRequest; use YoanBernabeu\MusicGptBundle\Enum\ConversionType; class WorkflowController { public function __construct( private readonly MusicAIServiceInterface $musicAI, private readonly ConversionServiceInterface $conversion ) {} public function generateAndWait(): void { // 1. Generate music $request = new MusicAIRequest(prompt: 'A relaxing piano melody'); $response = $this->musicAI->generate($request); $taskId = $response->getTaskId(); // 2. Poll for completion $maxAttempts = 30; for ($i = 0; $i < $maxAttempts; $i++) { sleep(10); $details = $this->conversion->getByTaskId( $taskId, ConversionType::MUSIC_AI ); if ($details->isCompleted()) { echo "✅ Done!\n"; echo "Download: {$details->getAudioUrl1()}\n"; break; } if ($details->isFailed()) { echo "❌ Failed: {$details->getStatusMessage()}\n"; break; } echo "⏳ Processing... (attempt {$i}/{$maxAttempts})\n"; } } } ``` -------------------------------- ### Install Music GPT Bundle with Composer Source: https://github.com/yoanbernabeu/music-gpt-bundle/blob/main/README.md Install the Music GPT Bundle using Composer. If you are using Symfony Flex, the bundle is automatically registered. Otherwise, you need to manually add it to your `config/bundles.php` file. ```bash composer require yoanbernabeu/music-gpt-bundle ``` ```php return [ // ... YoanBernabeu\MusicGptBundle\MusicGptBundle::class => ['all' => true], ]; ``` -------------------------------- ### Example Git Commit Message Source: https://github.com/yoanbernabeu/music-gpt-bundle/blob/main/CONTRIBUTING.md Illustrates the recommended format for Git commit messages, emphasizing the use of present tense, imperative mood, and referencing issues. This helps maintain a clear and searchable commit history. ```git Add cache clearing functionality - Implement clearEndpointCache method - Implement clearAllCache method - Add tests for cache clearing Fixes #123 ``` -------------------------------- ### Generate Music with Simple Prompt - PHP Source: https://context7.com/yoanbernabeu/music-gpt-bundle/llms.txt Generates AI music using a simple natural language prompt. This example demonstrates creating a basic `MusicAIRequest` and handling the response, including task tracking and potential exceptions like `PaymentRequiredException` or `RateLimitException`. ```php musicAI->generate($request); // Response contains task tracking information echo "Task ID: {$response->getTaskId()}\n"; echo "Estimated completion time: {$response->getEta()} seconds\n"; // Music AI generates 2 versions by default $conversionIds = $response->getConversionIds(); echo "Version 1 ID: {$conversionIds[0]}\n"; echo "Version 2 ID: {$conversionIds[1]}\n"; } catch (YoanBernabeu\MusicGptBundle\Exception\PaymentRequiredException $e) { echo "Insufficient credits: {$e->getMessage()}\n"; } catch (YoanBernabeu\MusicGptBundle\Exception\RateLimitException $e) { echo "Rate limited. Retry after {$e->getRetryAfter()} seconds\n"; } } } ``` -------------------------------- ### Development Commands for Music GPT Bundle (Bash) Source: https://github.com/yoanbernabeu/music-gpt-bundle/blob/main/README.md Outlines essential command-line instructions for developing and maintaining the Music GPT Bundle. These commands cover running tests, checking code style, performing static analysis, and executing all checks simultaneously. This requires a Composer-based project setup. ```bash composer test composer cs-check composer cs-fix composer phpstan composer cs-check && composer phpstan && composer test ``` -------------------------------- ### PHP Strict Types and Type Hinting Example Source: https://github.com/yoanbernabeu/music-gpt-bundle/blob/main/CONTRIBUTING.md Demonstrates the use of strict types and type hints in PHP for improved code quality and predictability. This snippet shows a function with a string parameter and a string return type. ```php declare(strict_types=1); function formatName(string $firstName): string { return "Hello, " . $firstName; } ``` -------------------------------- ### List and Browse All AI Voices - PHP Source: https://context7.com/yoanbernabeu/music-gpt-bundle/llms.txt Provides methods to retrieve all available AI voice models and to iterate through them using pagination. The `listAllVoices` method fetches a limited set of voices, while `browseAllVoicesPaginated` demonstrates a loop to fetch all voices across multiple pages. This is useful for getting an overview of all available voice options. ```php voice->getAllVoices(limit: 100, page: 0); echo "Total voices available: {$response->getTotal()}\n"; echo "Showing: " . count($response->getVoices()) . " voices\n\n"; foreach ($response->getVoices() as $voice) { echo "{$voice->getVoiceName()} (ID: {$voice->getVoiceId()})\n"; } } public function browseAllVoicesPaginated(): void { // Iterate through all voices with pagination $page = 0; $limit = 20; $allVoiceNames = []; do { $response = $this->voice->getAllVoices($limit, $page); foreach ($response->getVoices() as $voice) { $allVoiceNames[] = $voice->getVoiceName(); } echo "Loaded page {$page}...\n"; $page++; } while (($page * $limit) < $response->getTotal()); echo "Total voices loaded: " . count($allVoiceNames) . "\n"; } } ``` -------------------------------- ### Track Conversion Status using ConversionServiceInterface in PHP Source: https://github.com/yoanbernabeu/music-gpt-bundle/blob/main/README.md Provides examples of checking the status and retrieving results for various conversion types (Music AI, Cover, Text-to-Speech, Extraction) using the ConversionServiceInterface. It handles completed, processing, and failed states and extracts relevant URLs. ```php use YoanBernabeu\MusicGptBundle\Contract\ConversionServiceInterface; use YoanBernabeu\MusicGptBundle\Enum\ConversionType; class ConversionController { public function __construct( private readonly ConversionServiceInterface $conversion ) {} public function checkStatus(): void { // Get details by Task ID $details = $this->conversion->getByTaskId( taskId: 'task_123456', conversionType: ConversionType::MUSIC_AI ); if ($details->isCompleted()) { echo "✅ Completed!\n"; echo "Audio 1: {$details->getAudioUrl1()}\n"; echo "Audio 2: {$details->getAudioUrl2()}\n"; } elseif ($details->isProcessing()) { echo "⏳ Processing: {$details->getStatus()}\n"; } elseif ($details->isFailed()) { echo "❌ Failed: {$details->getStatusMessage()}\n"; } } public function getByConversionId(): void { // Get details by Conversion ID $details = $this->conversion->getByConversionId( conversionId: 'conv_789012', conversionType: ConversionType::COVER ); if ($details->isCompleted()) { echo "Audio: {$details->getAudioUrl()}\n"; echo "Video: {$details->getVideoUrl()}\n"; echo "Cover: {$details->getImageUrl()}\n"; } } public function checkTextToSpeech(): void { // Check Text To Speech conversion $details = $this->conversion->getByTaskId( taskId: 'task_tts_123', conversionType: ConversionType::TEXT_TO_SPEECH ); if ($details->isCompleted()) { echo "✅ Speech generated!\n"; echo "Audio (MP3): {$details->getAudioUrl()}\n"; echo "Audio (WAV): {$details->getAudioUrlWav()}\n"; } } public function checkExtraction(): void { // Check Extraction conversion $details = $this->conversion->getByTaskId( taskId: 'task_extract_456', conversionType: ConversionType::EXTRACTION ); if ($details->isCompleted()) { echo "✅ Stems extracted!\n"; echo "Vocals: {$details->getVocalsUrl()}\n"; echo "Instrumental: {$details->getInstrumentalUrl()}\n"; } } } ``` -------------------------------- ### Extract Multiple Instruments with PHP Source: https://context7.com/yoanbernabeu/music-gpt-bundle/llms.txt Shows how to extract a comprehensive set of instruments from a local audio file. This example specifies multiple stems including vocals, drums, bass, guitar, piano, and strings using the `ExtractionRequest` DTO. It returns a task ID for the extraction process. ```php extraction->extractStems($request); echo "Multi-stem extraction: {$response->getTaskId()}\n"; } // ... other methods ... } ``` -------------------------------- ### Run Tests with Coverage Source: https://github.com/yoanbernabeu/music-gpt-bundle/blob/main/CONTRIBUTING.md Executes project tests and generates an HTML report of code coverage. This helps identify areas of the codebase that are not adequately tested. ```bash composer test -- --coverage-html coverage/ ``` -------------------------------- ### Configure Music GPT API Key Source: https://github.com/yoanbernabeu/music-gpt-bundle/blob/main/README.md Configure the Music GPT API key in your Symfony application. Create a `config/packages/music_gpt.yaml` file and add your API key from environment variables. Ensure the `MUSIC_GPT_API_KEY` is set in your `.env` file. ```yaml music_gpt: api: api_key: '%env(MUSIC_GPT_API_KEY)%' ``` ```env MUSIC_GPT_API_KEY=your_api_key_here ``` -------------------------------- ### Run Project Tests with Composer Source: https://github.com/yoanbernabeu/music-gpt-bundle/blob/main/CONTRIBUTING.md Executes all automated tests for the project using Composer's test script. It ensures code quality and functionality before merging changes. ```bash composer test ``` -------------------------------- ### Run Static Analysis with PHPStan Source: https://github.com/yoanbernabeu/music-gpt-bundle/blob/main/CONTRIBUTING.md Performs static analysis on the project code using PHPStan to detect bugs and type errors. This helps catch potential issues before runtime. ```bash composer phpstan ``` -------------------------------- ### Generate Music with Advanced Parameters - PHP Source: https://context7.com/yoanbernabeu/music-gpt-bundle/llms.txt Demonstrates generating music with advanced parameters like style, lyrics, voice model, and webhook URL for asynchronous notifications. It also shows how to generate instrumental-only tracks. Error handling for payment and rate limits is included. ```php musicAI->generate($request); // Store task ID for later status checking $this->saveTaskId($response->getTaskId()); echo "Music generation started!\n"; echo "Task: {$response->getTaskId()}\n"; echo "ETA: {$response->getEta()}s\n"; } public function generateInstrumental(): void { // Generate instrumental only (no vocals) $request = new MusicAIRequest( musicStyle: 'Jazz Fusion', prompt: 'Smooth saxophone melody with piano accompaniment', makeInstrumental: true ); $response = $this->musicAI->generate($request); echo "Instrumental track ID: {$response->getTaskId()}\n"; } } ``` -------------------------------- ### Search and List Voices using VoiceServiceInterface in PHP Source: https://github.com/yoanbernabeu/music-gpt-bundle/blob/main/README.md Demonstrates how to search for voices by name, with or without pagination, and how to list all available voices using the VoiceServiceInterface. It shows how to retrieve voice information, total counts, and pagination details. ```php use YoanBernabeu\MusicGptBundle\Contract\VoiceServiceInterface; class VoiceController { public function __construct( private readonly VoiceServiceInterface $voice ) {} public function searchVoices(): void { // Search for voices by name $response = $this->voice->searchVoices('Drake'); echo "Found {$response->getTotal()} voices\n"; foreach ($response->getVoices() as $voice) { echo "ID: {$voice->getVoiceId()} - Name: {$voice->getVoiceName()}\n"; } } public function searchWithPagination(): void { // Search with pagination $response = $this->voice->searchVoices( query: 'Taylor', limit: 50, page: 0 ); echo "Page {$response->getPage()} of " . ceil($response->getTotal() / $response->getLimit()) . "\n"; } public function listAllVoices(): void { // Get all available voices $response = $this->voice->getAllVoices(limit: 100, page: 0); echo "Total voices available: {$response->getTotal()}\n"; echo "Showing: " . count($response->getVoices()) . " voices\n"; } public function browseVoices(): void { // Browse through all voices with pagination $page = 0; $limit = 20; do { $response = $this->voice->getAllVoices($limit, $page); foreach ($response->getVoices() as $voice) { echo "{$voice->getVoiceName()}\n"; } $page++; } while (($page * $limit) < $response->getTotal()); } } ``` -------------------------------- ### Create AI Voice Cover with Webhook Source: https://context7.com/yoanbernabeu/music-gpt-bundle/llms.txt Initiates an asynchronous AI voice cover creation process from an audio URL, providing a webhook URL for completion notifications. The request includes the audio source, desired voice, and the callback URL for asynchronous updates. ```php cover->createCover($request); // Your webhook will receive notification when complete } } ``` -------------------------------- ### Extract Basic Stems with PHP Source: https://context7.com/yoanbernabeu/music-gpt-bundle/llms.txt Demonstrates how to extract basic audio stems such as vocals and instrumentals from an audio URL. It utilizes the `ExtractionServiceInterface` and `ExtractionRequest` DTO to specify the audio source and desired stems. The output includes task and conversion IDs, along with an estimated time of arrival. ```php extraction->extractStems($request); echo "Extraction started\n"; echo "Task ID: {$response->getTaskId()}\n"; echo "Conversion ID: {$response->getConversionId()}\n"; echo "ETA: {$response->getEta()} seconds\n"; } // ... other methods ... } ``` -------------------------------- ### PHP: Generate Music and Wait for Completion Source: https://context7.com/yoanbernabeu/music-gpt-bundle/llms.txt This PHP script demonstrates how to generate music using the MusicAIServiceInterface and then poll for its completion using the ConversionServiceInterface. It handles task initiation, status checking, error handling (including rate limiting), and downloading the generated audio files. ```php musicAI->generate($request); $taskId = $response->getTaskId(); echo "\uD83C\uDFB6 Music generation started\n"; echo "Task ID: {$taskId}\n"; echo "Estimated time: {$response->getEta()}s\n\n"; // Step 2: Poll for completion $maxAttempts = 60; $pollInterval = 10; // seconds for ($attempt = 1; $attempt <= $maxAttempts; $attempt++) { sleep($pollInterval); try { $details = $this->conversion->getByTaskId( $taskId, ConversionType::MUSIC_AI ); if ($details->isCompleted()) { echo "\n\u2705 Generation complete!\n"; echo "Download URLs:\n"; echo " Version 1 (MP3): {$details->getAudioUrl1()}\n"; echo " Version 2 (MP3): {$details->getAudioUrl2()}\n"; echo " Version 1 (WAV): {$details->getAudioWavUrl1()}\n"; echo " Version 2 (WAV): {$details->getAudioWavUrl2()}\n"; // Download files $this->downloadAudio($details->getAudioUrl1(), 'version1.mp3'); $this->downloadAudio($details->getAudioUrl2(), 'version2.mp3'); break; } if ($details->isFailed()) { echo "\n\u274C Generation failed!\n"; echo "Error: {$details->getStatusMessage()}\n"; break; } echo "\uD83D\uDD50 Processing... ({$details->getStatus()}) - Attempt {$attempt}/{$maxAttempts}\n"; } catch (\YoanBernabeu\MusicGptBundle\Exception\RateLimitException $e) { echo "Rate limited. Waiting {$e->getRetryAfter()}s before retry...\n"; sleep($e->getRetryAfter()); } } if ($attempt > $maxAttempts) { echo "\n\u26A0 Timeout: Maximum polling attempts reached\n"; } } private function downloadAudio(string $url, string $filename): void { $content = file_get_contents($url); file_put_contents("/var/www/downloads/{$filename}", $content); echo "Downloaded: {$filename}\n"; } public function batchGenerationWorkflow(): void { $prompts = [ 'Upbeat rock anthem', 'Calm meditation music', 'Energetic dance track' ]; $taskIds = []; // Start all generations foreach ($prompts as $prompt) { $request = new MusicAIRequest(prompt: $prompt); $response = $this->musicAI->generate($request); $taskIds[] = $response->getTaskId(); echo "Started: {$prompt} (Task: {$response->getTaskId()})\n"; } // Monitor all tasks $completed = []; $maxAttempts = 60; for ($attempt = 1; $attempt <= $maxAttempts; $attempt++) { sleep(10); foreach ($taskIds as $taskId) { if (isset($completed[$taskId])) { continue; } $details = $this->conversion->getByTaskId($taskId, ConversionType::MUSIC_AI); if ($details->isCompleted()) { $completed[$taskId] = true; echo "✅ Completed: {$taskId}\n"; } } if (count($completed) === count($taskIds)) { echo "\n\ud83c\udf89 All generations complete!\n"; break; } $remaining = count($taskIds) - count($completed); echo "\uD83D\uDD50 {$remaining} tasks remaining...\n"; } } } ``` -------------------------------- ### Asynchronous Text-to-Speech with Webhook Source: https://context7.com/yoanbernabeu/music-gpt-bundle/llms.txt Initiates an asynchronous text-to-speech conversion with a specified voice and a webhook URL for notifications upon completion. This allows for background processing of speech generation without blocking the user interface. ```php textToSpeech->createTextToSpeech($request); // Webhook receives notification when audio is ready } } ``` -------------------------------- ### Generate Music with AI using Music GPT Bundle Source: https://github.com/yoanbernabeu/music-gpt-bundle/blob/main/README.md Generate AI music using the `MusicAIServiceInterface`. This service allows you to create music from simple text prompts or with advanced options like custom music styles, lyrics, and voice models. The response includes a task ID and estimated time of arrival (ETA). ```php use YoanBernabeu\MusicGptBundle\Contract\MusicAIServiceInterface; use YoanBernabeu\MusicGptBundle\DTO\MusicAI\MusicAIRequest; class MusicController { public function __construct( private readonly MusicAIServiceInterface $musicAI ) {} public function generate(): void { // Simple prompt $request = new MusicAIRequest( prompt: 'A cheerful song about coding in PHP' ); $response = $this->musicAI->generate($request); echo "Task ID: {$response->getTaskId()}\n"; echo "ETA: {$response->getEta()} seconds\n"; } public function generateAdvanced(): void { // With custom style and vocals $request = new MusicAIRequest( musicStyle: 'Lo-fi Hip Hop', lyrics: 'Coding all night long...', voiceId: 'Drake', makeInstrumental: false ); $response = $this->musicAI->generate($request); // The API generates 2 versions [$version1, $version2] = $response->getConversionIds(); } } ``` -------------------------------- ### Create AI Voice Cover from URL Source: https://context7.com/yoanbernabeu/music-gpt-bundle/llms.txt Generates an AI voice cover by providing an audio URL and a target voice ID. This method initiates a task and returns a task ID, conversion ID, and estimated time of arrival (ETA). It includes error handling for validation exceptions. ```php cover->createCover($request); echo "Cover creation started\n"; echo "Task ID: {$response->getTaskId()}\n"; echo "Conversion ID: {$response->getConversionId()}\n"; echo "ETA: {$response->getEta()} seconds\n"; } catch (\YoanBernabeu\MusicGptBundle\Exception\ValidationException $e) { echo "Validation failed: {$e->getMessage()}\n"; print_r($e->getErrors()); } } } ``` -------------------------------- ### Fix Code Style Automatically Source: https://github.com/yoanbernabeu/music-gpt-bundle/blob/main/CONTRIBUTING.md Automatically formats the project's code to comply with PSR-12 coding standards and custom rules. This command helps maintain a consistent codebase. ```bash composer cs-fix ``` -------------------------------- ### Voice Search and Listing API Source: https://github.com/yoanbernabeu/music-gpt-bundle/blob/main/README.md APIs for searching voices by name and listing all available voices with pagination support. ```APIDOC ## GET /voices/search ### Description Searches for voices based on a query string. Supports pagination and limiting results. ### Method GET ### Endpoint /voices/search ### Parameters #### Query Parameters - **query** (string) - Required - The search term for voices. - **limit** (integer) - Optional - The maximum number of results to return per page. Defaults to 20. - **page** (integer) - Optional - The page number of results to retrieve. Defaults to 0. ### Request Example ```json { "query": "Drake", "limit": 50, "page": 0 } ``` ### Response #### Success Response (200) - **voices** (array) - Array of VoiceInfo objects. - **total** (integer) - Total number of voices available. - **limit** (integer) - Number of results per page. - **page** (integer) - Current page number. #### Response Example ```json { "voices": [ { "voiceId": "voice_123", "voiceName": "Drake" } ], "total": 100, "limit": 50, "page": 0 } ``` ## GET /voices/all ### Description Retrieves a list of all available voices. Supports pagination and limiting results. ### Method GET ### Endpoint /voices/all ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of results to return per page. Defaults to 20. - **page** (integer) - Optional - The page number of results to retrieve. Defaults to 0. ### Request Example ```json { "limit": 100, "page": 0 } ``` ### Response #### Success Response (200) - **voices** (array) - Array of VoiceInfo objects. - **total** (integer) - Total number of voices available. - **limit** (integer) - Number of results per page. - **page** (integer) - Current page number. #### Response Example ```json { "voices": [ { "voiceId": "voice_456", "voiceName": "Taylor Swift" } ], "total": 500, "limit": 100, "page": 0 } ``` ``` -------------------------------- ### Create AI Voice Covers with Music GPT Bundle Source: https://github.com/yoanbernabeu/music-gpt-bundle/blob/main/README.md Create AI voice covers using the `CoverServiceInterface`. This service allows you to generate covers from an audio URL or a local audio file, specifying a voice ID and optionally adjusting the pitch. The response provides a task ID and conversion ID. ```php use YoanBernabeu\MusicGptBundle\Contract\CoverServiceInterface; use YoanBernabeu\MusicGptBundle\DTO\Cover\CoverRequest; class CoverController { public function __construct( private readonly CoverServiceInterface $cover ) {} public function create(): void { // From URL $request = new CoverRequest( audioUrl: 'https://example.com/song.mp3', voiceId: 'Drake' ); $response = $this->cover->createCover($request); echo "Task ID: {$response->getTaskId()}\n"; echo "Conversion ID: {$response->getConversionId()}\n"; } public function createWithPitch(): void { // From local file with pitch adjustment $request = new CoverRequest( audioFile: '/path/to/audio.wav', voiceId: 'Taylor Swift', pitch: -2 // -12 to +12 semitones ); $response = $this->cover->createCover($request); } } ``` -------------------------------- ### Handle Various Music GPT API Exceptions in PHP Source: https://context7.com/yoanbernabeu/music-gpt-bundle/llms.txt This PHP code demonstrates how to catch and handle specific exceptions thrown by the MusicAIServiceInterface, such as AuthenticationException, PaymentRequiredException, RateLimitException, ValidationException, NotFoundException, and ApiException. It provides user-friendly messages and specific actions for each error type, including retrying requests with exponential backoff for rate limits. ```php musicAI->generate($request); echo "Success! Task ID: {$response->getTaskId()}\n"; } catch (AuthenticationException $e) { // Invalid API key (401/403) echo "❌ Authentication failed: {$e->getMessage()}\n"; echo "Check your MUSIC_GPT_API_KEY environment variable\n"; } catch (PaymentRequiredException $e) { // Insufficient credits (402) echo "❌ Payment required: {$e->getMessage()}\n"; echo "Please add credits to your account at musicgpt.com\n"; } catch (RateLimitException $e) { // Too many requests (429) $retryAfter = $e->getRetryAfter(); echo "❌ Rate limited: {$e->getMessage()}\n"; echo "Retry after: {$retryAfter} seconds\n"; // Implement exponential backoff if ($retryAfter) { sleep($retryAfter); // Retry request } } catch (ValidationException $e) { // Invalid parameters (400/422) echo "❌ Validation error: {$e->getMessage()}\n"; $errors = $e->getErrors(); if (!empty($errors)) { echo "Validation errors:\n"; foreach ($errors as $field => $messages) { echo " {$field}: " . implode(', ', (array)$messages) . "\n"; } } } catch (NotFoundException $e) { // Resource not found (404) echo "❌ Not found: {$e->getMessage()}\n"; echo "Endpoint: {$e->getEndpoint()}\n"; } catch (ApiException $e) { // General API error (500, etc.) echo "❌ API error: {$e->getMessage()}\n"; echo "Status code: {$e->getStatusCode()}\n"; echo "Endpoint: {$e->getEndpoint()}\n"; } catch (MusicGptException $e) { // Base exception for all bundle exceptions echo "❌ MusicGPT error: {$e->getMessage()}\n"; } catch (\Exception $e) { // Unexpected errors echo "❌ Unexpected error: {$e->getMessage()}\n"; } } public function handleRateLimitWithRetry(): void { $request = new MusicAIRequest(prompt: 'Generate music'); $maxRetries = 3; $attempt = 0; while ($attempt < $maxRetries) { try { $response = $this->musicAI->generate($request); echo "Success after {$attempt} retries\n"; return; } catch (RateLimitException $e) { $attempt++; $retryAfter = $e->getRetryAfter() ?? 60; if ($attempt >= $maxRetries) { echo "Max retries reached. Giving up.\n"; throw $e; } echo "Rate limited. Retry {$attempt}/{$maxRetries} in {$retryAfter}s\n"; sleep($retryAfter); } } } public function validateBeforeRequest(): void { // Client-side validation to avoid API errors $prompt = ''; $voiceId = 'InvalidVoice'; if (empty($prompt)) { echo "Error: Prompt cannot be empty\n"; return; } if (strlen($prompt) < 10) { echo "Error: Prompt too short (minimum 10 characters)\n"; return; } try { $request = new MusicAIRequest( prompt: $prompt, voiceId: $voiceId ); $response = $this->musicAI->generate($request); } catch (ValidationException $e) { // API validation failed - log for debugging error_log("Validation failed: " . json_encode($e->getErrors())); echo "Validation error: {$e->getMessage()}\n"; } } } ``` -------------------------------- ### Extract Stems with Preprocessing in PHP Source: https://context7.com/yoanbernabeu/music-gpt-bundle/llms.txt Illustrates extracting vocals and instrumentals while applying preprocessing options to clean the audio. This includes denoising, dereverberation, and de-echoing. The `ExtractionRequest` DTO is used to specify the audio URL, stems, and the desired preprocessing steps. The task ID is returned upon initiation. ```php extraction->extractStems($request); echo "Clean vocal extraction: {$response->getTaskId()}\n"; } // ... other methods ... } ``` -------------------------------- ### Check Code Style with Composer Source: https://github.com/yoanbernabeu/music-gpt-bundle/blob/main/CONTRIBUTING.md Verifies that the project's code adheres to the defined PSR-12 coding standards and additional rules specified in .php-cs-fixer.dist.php. This command checks for style violations without modifying files. ```bash composer cs-check ``` -------------------------------- ### Generate Text to Speech Source: https://github.com/yoanbernabeu/music-gpt-bundle/blob/main/README.md Converts text into speech using specified voice parameters. Supports basic text-to-speech, voice cloning via sample audio, and asynchronous notifications via webhooks. Dependencies include the TextToSpeechServiceInterface. Outputs a task ID and ETA. ```php use YoanBernabeu\MusicGptBundle\Contract\TextToSpeechServiceInterface; use YoanBernabeu\MusicGptBundle\DTO\TextToSpeech\TextToSpeechRequest; class TextToSpeechController { public function __construct( private readonly TextToSpeechServiceInterface $textToSpeech ) {} public function create(): void { // Simple text to speech with voice ID $request = new TextToSpeechRequest( text: 'Hello world, this is a test of the text to speech feature.', gender: 'male', voiceId: 'Drake' ); $response = $this->textToSpeech->createTextToSpeech($request); echo "Task ID: {$response->getTaskId()}\n"; echo "ETA: {$response->getEta()} seconds\n"; } public function createWithSampleAudio(): void { // Using a sample audio URL for voice cloning $request = new TextToSpeechRequest( text: 'The character Sherlock Holmes first appeared in print in 1887.', gender: 'female', sampleAudioUrl: 'https://example.com/voice-sample.mp3' ); $response = $this->textToSpeech->createTextToSpeech($request); } public function createWithWebhook(): void { // With webhook for async notification $request = new TextToSpeechRequest( text: 'When I think of superheroes I think of super humans.', gender: 'male', voiceId: 'Drake', webhookUrl: 'https://example.com/webhook' ); $response = $this->textToSpeech->createTextToSpeech($request); } } ``` -------------------------------- ### Text To Speech Generation API Source: https://github.com/yoanbernabeu/music-gpt-bundle/blob/main/README.md This API endpoint allows you to convert text into speech. You can specify voice characteristics, use sample audio for voice cloning, or receive asynchronous notifications via a webhook. ```APIDOC ## POST /text-to-speech ### Description Converts the provided text into speech using specified voice parameters. Supports voice cloning via sample audio and webhook notifications for task completion. ### Method POST ### Endpoint /text-to-speech ### Parameters #### Request Body - **text** (string) - Required - The text content to be converted to speech. - **gender** (string) - Required - The desired gender for the voice ('male' or 'female'). - **voiceId** (string) - Optional - The ID of a pre-defined voice model (e.g., 'Drake', 'Adele'). - **sampleAudioUrl** (string) - Optional - A URL to an audio file to be used for voice cloning. This takes priority over `voiceId`. - **webhookUrl** (string) - Optional - A URL to receive asynchronous notifications when the speech generation is complete. ### Request Example ```json { "text": "Hello world, this is a test of the text to speech feature.", "gender": "male", "voiceId": "Drake", "webhookUrl": "https://example.com/webhook" } ``` ### Response #### Success Response (200) - **taskId** (string) - The unique identifier for the generated speech task. - **eta** (integer) - Estimated time in seconds until the task is completed. #### Response Example ```json { "taskId": "xyz789", "eta": 60 } ``` ```