### Python Error Handling Example Source: https://docs.musicgpt.com/api-documentation/utilities/error A practical Python code example demonstrating how to handle various HTTP status codes returned by the MusicGPT API, including success, client errors, and server errors. ```APIDOC ## How to Handle Errors in Your Code (Python Example) This example illustrates how to implement error handling logic when making requests to the MusicGPT API using Python. ### Python Code Snippet ```python import requests url = "https://api.musicgpt.com/data" headers = { "Authorization": "Bearer " } try: response = requests.get(url, headers=headers) response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx) if response.status_code == 200: print("Request successful:", response.json()) # Additional specific checks can be added here if needed for particular 2xx codes except requests.exceptions.HTTPError as e: status_code = e.response.status_code if status_code == 400: print(f"Error {status_code}: Bad Request. Please check your input parameters.") elif status_code == 402: print(f"Error {status_code}: Payment Required. Please check your account balance or payment method.") elif status_code == 403: print(f"Error {status_code}: Forbidden. Check your API key permissions.") elif status_code == 404: print(f"Error {status_code}: Not Found. The requested resource does not exist.") elif status_code == 409: print(f"Error {status_code}: Conflict. There is a conflict with the resource state.") elif status_code == 422: print(f"Error {status_code}: Unprocessable Entity. Review the request body for validation errors.") elif status_code == 429: print(f"Error {status_code}: Rate Limit Exceeded. Please try again later.") elif status_code >= 500: print(f"Error {status_code}: Internal Server Error. Please try again later or contact support.") else: print(f"An unexpected HTTP error occurred: {status_code} - {e.response.text}") except requests.exceptions.RequestException as e: print(f"A network or request-related error occurred: {e}") ``` ``` -------------------------------- ### Transcribe Audio using Go Source: https://docs.musicgpt.com/api-documentation/conversions/audiotranscription This Go code snippet illustrates how to interact with the MusicGPT API for audio transcription. It covers both transcribing from a URL and uploading a local audio file. The code uses the `net/http` package for requests and `mime/multipart` for file uploads, requiring an API key for authentication. Error handling is minimal in this example. ```Go package main import ( "bytes" "fmt" "io" "mime/multipart" "net/http" "os" "strings" ) func main() { url := "https://api.musicgpt.com/api/public/v1/audio_transcribe" apiKey := "<<>>" // Option 1: URL payload := "audio_url=https://example.com/audio.mp3&language=en&translate=true&transcription_format=srt&word_timestamps=true" req, _ := http.NewRequest("POST", url, strings.NewReader(payload)) req.Header.Add("Authorization", apiKey) res, _ := http.DefaultClient.Do(req) defer res.Body.Close() body, _ := io.ReadAll(res.Body) fmt.Println(string(body)) // Option 2: File Upload file, _ := os.Open("audio.mp3") defer file.Close() bodyBuf := &bytes.Buffer{} writer := multipart.NewWriter(bodyBuf) writer.WriteField("language", "en") writer.WriteField("translate", "false") writer.WriteField("transcription_format", "plain_text") writer.WriteField("word_timestamps", "true") part, _ := writer.CreateFormFile("audio_file", "audio.mp3") io.Copy(part, file) writer.Close() req, _ = http.NewRequest("POST", url, bodyBuf) req.Header.Add("Authorization", apiKey) req.Header.Add("Content-Type", writer.FormDataContentType()) res, _ = http.DefaultClient.Do(req) defer res.Body.Close() body, _ = io.ReadAll(res.Body) fmt.Println(string(body)) } ``` -------------------------------- ### Webhook Integration Guide Source: https://docs.musicgpt.com/api-documentation/index/webhook This section outlines the process of using webhooks for Musicgpt asynchronous tasks. It covers how to set the webhook URL, what to expect in the POST request from Musicgpt upon task completion, and how to handle the incoming payload. ```APIDOC ## Webhook Integration Webhooks allow Musicgpt to notify your application the moment an asynchronous task (like music generation, voice cloning, or instrumental extraction) is completed. This eliminates the need for constant polling of the API. ### How It Works 1. **Set the `webhook_url`**: Provide your server's URL when submitting a conversion request. 2. **Receive POST Request**: Musicgpt will send a POST request to your specified `webhook_url` when the task is finished. 3. **Process Payload**: Your server can parse the received JSON payload to access details like the audio URL and task status. ### Sample Webhook Payload When a task is completed, Musicgpt sends a JSON payload containing: * **`task_id`** (string): The unique identifier for the task. * **`status`** (string): The completion status (e.g., "COMPLETED"). * **`status_msg`** (string): A message indicating the status. * **`conversion_type`** (string): The type of conversion performed (e.g., "MUSIC_AI"). * **`audio_url`** (string): The URL to the generated audio file. * **`title`** (string): The title of the generated content. * **`conversion_cost`** (number): The cost associated with the conversion. * **`createdAt`** (string): The timestamp when the task was created. * **`updatedAt`** (string): The timestamp when the task was last updated. **Example Payload:** ```json { "task_id": "12345678-abcd-1234-efgh-567890abcdef", "status": "COMPLETED", "status_msg": "Conversion successful", "conversion_type": "MUSIC_AI", "audio_url": "https://musicgpt.s3.amazonaws.com/audiofile.mp3", "title": "Generated Song", "conversion_cost": 1.25, "createdAt": "2025-01-01T12:00:00Z", "updatedAt": "2025-01-01T12:05:00Z" } ``` ### Preliminary Response Upon initiating a conversion request, Musicgpt provides an immediate preliminary response confirming the task acceptance. This response includes: * **`success`** (boolean): Indicates if the task initiation was successful. * **`task_id`** (string): A unique ID for tracking the task. **Example Preliminary Response:** ```json { "success": true, "task_id": "12345678-abcd-1234-efgh-567890abcdef" } ``` ### Alternative: Get Conversion by ID If you cannot use webhooks (e.g., running code on a client device or lacking a public server), you can manually check the conversion status using the "Get Conversion by ID" endpoint. Refer to `/api-documentation/endpoint/CheckStatus` for details. ``` -------------------------------- ### Extend Task API - Successful Response Example Source: https://docs.musicgpt.com/api-documentation/conversions/extend This example demonstrates the JSON response structure for a successfully initiated extend task. It includes a success status, a confirmation message, task and conversion identifiers, estimated processing time, and a credit estimate. ```json { "success": true, "message": "Extend request submitted successfully", "task_id": "task-extend-789", "conversion_id_1": "extend-a1b2", "conversion_id_2": "extend-c3d4", "eta": 38, "credit_estimate": 42 } ``` -------------------------------- ### Inpaint Audio with File Upload using Python - MusicGPT API Source: https://docs.musicgpt.com/api-documentation/endpoint/inpaint This code example shows how to perform audio inpainting using the MusicGPT API by uploading an audio file directly. It includes setting up the request headers with an API key, defining the inpainting parameters, and attaching the audio file in binary mode. An optional webhook URL can be provided for asynchronous results. ```Python import requests url = "https://api.musicgpt.com/api/public/v1/inpaint" headers = {"Authorization": ""} data = { "prompt": "Add a soft guitar solo here", "replace_start_at": 12.5, "replace_end_at": 20.0, "lyrics": "This is where my story begins", "gender": "male", "webhook_url": "https://example.com/webhook" } # Option 2: File Upload with open("song.mp3", "rb") as f: files = {"audio_file": f} response = requests.post(url, headers=headers, data=data, files=files) # print(response.json()) ``` -------------------------------- ### Music AI API - POST Request Example (YAML) Source: https://docs.musicgpt.com/api-documentation/conversions/musicai This YAML snippet defines the structure for a POST request to the /MusicAI endpoint. It includes parameters for prompt, music style, lyrics, instrumental/vocal options, voice ID, and webhook URL. It also details the expected success and error responses. ```yaml paths: path: /MusicAI method: post servers: - url: https://api.musicgpt.com/api/public/v1 description: Production server request: security: - title: ApiKeyAuth parameters: query: {} header: Authorization: type: apiKey cookie: {} parameters: path: {} query: {} header: {} cookie: {} body: application/json: schemaArray: - type: object properties: prompt: allOf: - type: string description: >- A natural language prompt for music generation. Keep it under 280 characters for guaranteed results, but detailed—the clearer and more descriptive it is, the better the outcome. music_style: allOf: - type: string description: Style of music to generate (e.g., Rock, Pop) lyrics: allOf: - type: string description: Custom lyrics for the generated music make_instrumental: allOf: - type: boolean description: Whether to make the music instrumental default: false vocal_only: allOf: - type: boolean description: Whether to generate only vocals of output audio default: false voice_id: allOf: - type: string description: Voice model to convert generated audio webhook_url: allOf: - type: string description: URL for callback upon completion required: true examples: example: value: prompt: music_style: lyrics: make_instrumental: false vocal_only: false voice_id: webhook_url: response: '200': application/json: schemaArray: - type: object properties: success: allOf: - type: boolean message: allOf: - type: string task_id: allOf: - type: string conversion_id_1: allOf: - type: string conversion_id_2: allOf: - type: string eta: allOf: - type: integer examples: example: value: success: true message: Message published to queue task_id: 4fc2cdba-005d-4d14-a208-5fb02a2809da conversion_id_1: 05092d5c-f8b1-4c96-a4a3-45bc00de6268 conversion_id_2: 52fcd3b6-3925-41ed-b4c6-aee17a29e40b eta: 154 description: Successful response '402': application/json: schemaArray: - type: object properties: success: allOf: - type: boolean error: allOf: - type: string examples: example: value: success: false error: Insufficient credit balance description: Payment Required '500': application/json: schemaArray: - type: object properties: success: allOf: - type: boolean error: allOf: - type: string examples: example: value: success: false error: Internal Server Error description: Internal Server Error deprecated: false type: path components: schemas: {} ``` -------------------------------- ### VoiceChanger API Endpoint - Python and PHP Examples Source: https://docs.musicgpt.com/api-documentation/endpoint/voicetovoice Code samples for interacting with the VoiceChanger API endpoint. Supports both audio URL input and file upload. Includes options for background noise removal, pitch adjustment, and webhook notifications. Requires an API key for authentication. ```Python import requests url = "https://api.musicgpt.com/api/public/v1/VoiceChanger" payload = { "audio_url": "", "voice_id": "", "remove_background": "", "pitch": "", "webhook_url": "" } # For file upload instead of URL: # files = {'audio_file': open('filepath', 'rb')} headers = { "Authorization": "" } response = requests.post(url, data=payload, headers=headers) # For file upload: # response = requests.post(url, data=payload, files=files, headers=headers) print(response.text) ``` ```PHP "; // For URL-based processing $data = [ "audio_url" => "", "voice_id" => "", "remove_background" => 0, // 0 or 1 "pitch" => 0, // -12 to +12 "webhook_url" => "" ]; // For file upload (uncomment and replace) // $data = ["voice_id" => ""]; // $file = new CURLFile('path/to/audio.wav', 'audio/wav', 'audio_file'); $headers = [ "Authorization: " . $apiKey ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // For file upload: // curl_setopt($ch, CURLOPT_POSTFIELDS, array_merge($data, ['audio_file' => $file])); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` -------------------------------- ### Initiate Audio Trim (POST /api/public/v1/audio_cutter) - Go Source: https://docs.musicgpt.com/api-documentation/conversions/audiocutter This Go code snippet demonstrates how to make a POST request to the audio_cutter endpoint. It sends an audio URL, start and end times, and the desired output format. The request includes an Authorization token for authentication. It prints the response body from the API. ```go package main import ( "fmt" "io" "net/http" "strings" ) func main() { url := "https://api.musicgpt.com/api/public/v1/audio_cutter" token := "" data := "audio_url=https://example.com/input_audio.mp3&start_time=10500&end_time=45000&output_extension=mp3" req, _ := http.NewRequest("POST", url, strings.NewReader(data)) req.Header.Add("Authorization", token) res, _ := http.DefaultClient.Do(req) defer res.Body.Close() body, _ := io.ReadAll(res.Body) fmt.Println(string(body)) } ``` -------------------------------- ### Call Voice Changer API with File Upload (Java) Source: https://docs.musicgpt.com/api-documentation/endpoint/voicetovoice This Java code example demonstrates how to upload an audio file using the MusicGPT Voice Changer API with OkHttp. It sets up a multipart request including the audio file and other necessary parameters, with authentication handled via an API key. The API response is then printed. ```Java import okhttp3.*; import java.io.File; import java.io.IOException; public class VoiceChanger { public static void main(String[] args) throws IOException { String url = "https://api.musicgpt.com/api/public/v1/VoiceChanger"; String apiKey = ""; // For URL-based processing /* RequestBody requestBody = new FormBody.Builder() .add("audio_url", "") .add("voice_id", "") .add("remove_background", "0") .add("pitch", "0") .add("webhook_url", "") .build(); */ // For file upload (uncomment and replace) File audioFile = new File("audio.wav"); RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("voice_id", "") .addFormDataPart("audio_file", "audio.wav", RequestBody.create(audioFile, MediaType.parse("audio/wav")), RequestBody.create(audioFile, MediaType.parse("audio/wav"))) .build(); Request request = new Request.Builder() .url(url) .post(requestBody) .header("Authorization", apiKey) .build(); OkHttpClient client = new OkHttpClient(); try (Response response = client.newCall(request).execute()) { System.out.println(response.body().string()); } } } ``` -------------------------------- ### Initiate Noise Removal via URL - Go Source: https://docs.musicgpt.com/api-documentation/conversions/denoise This Go code snippet demonstrates how to initiate the noise removal process by providing an audio file URL. It sends a POST request to the `/api/public/v1/denoise` endpoint with the audio URL and an optional webhook URL. The API key must be included in the Authorization header. The response will contain a task ID for tracking the conversion. ```Go package main import ( "bytes" "fmt" "io" "mime/multipart" "net/http" "os" "strings" ) func main() { url := "https://api.musicgpt.com/api/public/v1/denoise" headers := map[string]string{ "Authorization": "<<>>" } // Option 1: URL data := "audio_url=https://example.com/audio.m4a&webhook_url=" req, _ := http.NewRequest("POST", url, strings.NewReader(data)) for k, v := range headers { req.Header.Add(k, v) } res, _ := http.DefaultClient.Do(req) defer res.Body.Close() body, _ := io.ReadAll(res.Body) fmt.Println(string(body)) // Option 2: File Upload file, _ := os.Open("audio.m4a") defer file.Close() bodyBuf := &bytes.Buffer{} writer := multipart.NewWriter(bodyBuf) _ = writer.WriteField("webhook_url", "https://www.test.requestcatcher.com/test") part, _ := writer.CreateFormFile("audio_file", "audio.m4a") io.Copy(part, file) writer.Close() req, _ = http.NewRequest("POST", url, bodyBuf) req.Header.Add("Authorization", "<<>>") req.Header.Add("Content-Type", writer.FormDataContentType()) res, _ = http.DefaultClient.Do(req) defer res.Body.Close() body, _ = io.ReadAll(res.Body) fmt.Println(string(body)) } ``` -------------------------------- ### Fetch All Voices (OpenAPI Specification) Source: https://docs.musicgpt.com/api-documentation/endpoint/getAllVoices This OpenAPI specification defines the /getAllVoices endpoint for the MusicGPT API. It outlines the HTTP method (GET), base URL, request parameters (query parameters for pagination), and the expected JSON response structure for both success and error scenarios. The specification includes example responses to illustrate the data format. ```yaml GET /getAllVoices paths: path: /getAllVoices method: get servers: - url: https://api.musicgpt.com/api/public/v1 description: Production server request: security: - title: ApiKeyAuth parameters: query: {} header: Authorization: type: apiKey cookie: {} parameters: path: {} query: limit: schema: - type: integer required: false description: Maximum number of voices per page default: 20 page: schema: - type: integer required: false description: Page number for pagination default: 0 header: {} cookie: {} body: {} response: '200': application/json: schemaArray: - type: object properties: success: allOf: - type: boolean voices: allOf: - type: array items: type: object properties: voice_id: type: string voice_name: type: string limit: allOf: - type: integer page: allOf: - type: integer total: allOf: - type: integer examples: example: value: success: true voices: - voice_id: 00126f62-1f31-434a-abc6-a5e958a737e3 voice_name: Joji - voice_id: 0031cf05-6d3d-4c15-9115-d8236590b957 voice_name: Amy Winehouse limit: 20 page: 0 total: 3108 description: Successful response '500': application/json: schemaArray: - type: object properties: success: allOf: - type: boolean error: allOf: - type: string examples: example: value: success: false error: Internal Server Error description: Internal Server Error deprecated: false type: path components: schemas: {} ``` -------------------------------- ### GET /getAllVoices Source: https://docs.musicgpt.com/api-documentation/endpoint/getAllVoices Fetches a list of all available voices, with options for pagination and limiting the results. Includes voice IDs and names. ```APIDOC ## GET /getAllVoices ### Description Fetches all available voices with their IDs and names. Supports pagination through `limit` and `page` query parameters. ### Method GET ### Endpoint /getAllVoices ### Parameters #### Query Parameters - **limit** (integer) - Optional - Maximum number of voices per page (default: 20) - **page** (integer) - Optional - Page number for pagination (default: 0) ### Request Example ```bash GET /getAllVoices?limit=10&page=1 ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **voices** (array) - An array of voice objects, each containing `voice_id` (string) and `voice_name` (string). - **limit** (integer) - The limit applied to the number of voices returned. - **page** (integer) - The page number returned. - **total** (integer) - The total number of voices available. #### Response Example (200) ```json { "success": true, "voices": [ { "voice_id": "00126f62-1f31-434a-abc6-a5e958a737e3", "voice_name": "Joji" }, { "voice_id": "0031cf05-6d3d-4c15-9115-d8236590b957", "voice_name": "Amy Winehouse" } ], "limit": 20, "page": 0, "total": 3108 } ``` #### Error Response (500) - **success** (boolean) - Indicates if the request was successful (will be false). - **error** (string) - A message describing the server error. #### Response Example (500) ```json { "success": false, "error": "Internal Server Error" } ``` ``` -------------------------------- ### Initiate Audio Extraction Request (Go) Source: https://docs.musicgpt.com/api-documentation/conversions/extraction This Go code snippet demonstrates how to send a POST request to the MusicGPT API for audio extraction. It includes setting up multipart form data for the audio file, stems, preprocessing options, and webhook URL. It also handles setting the Authorization header and Content-Type. ```go package main import ( "bytes" "encoding/json" "fmt" "io" "mime/multipart" "net/http" "os" ) func main() { body := &bytes.Buffer{} writer := multipart.NewWriter(body) file, _ := os.Open("path_to_audio.mp3") part, _ := writer.CreateFormFile("audio_file", "path_to_audio.mp3") io.Copy(part, file) stems, _ := json.Marshal([]string{"vocals", "drums"}) preprocessing, _ := json.Marshal([]string{"Denoise"}) writer.WriteField("stems", string(stems)) writer.WriteField("preprocessing_options", string(preprocessing)) writer.WriteField("webhook_url", "http://webhook.musicgpt.com") writer.Close() req, _ := http.NewRequest("POST", "https://api.musicgpt.com/api/public/v1/Extraction", body) req.Header.Add("Authorization", "") req.Header.Add("Content-Type", writer.FormDataContentType()) client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() responseBody, _ := io.ReadAll(resp.Body) fmt.Println(string(responseBody)) } ``` -------------------------------- ### Initiate Audio Extraction in Go Source: https://docs.musicgpt.com/api-documentation/endpoint/extraction This Go snippet demonstrates how to create a multipart POST request to the MusicGPT API for audio extraction. It includes setting up the request body with an audio file, stem separation options, preprocessing steps, and a webhook URL. The code also handles setting the authorization header and content type, then sends the request using Go's net/http client. ```go package main import ( "bytes" "encoding/json" "fmt" "io" "mime/multipart" "net/http" "os" ) func main() { body := &bytes.Buffer{} writer := multipart.NewWriter(body) file, _ := os.Open("path_to_audio.mp3") part, _ := writer.CreateFormFile("audio_file", "path_to_audio.mp3") io.Copy(part, file) stems, _ := json.Marshal([]string{"vocals", "drums"}) preprocessing, _ := json.Marshal([]string{"Denoise"}) writer.WriteField("stems", string(stems)) writer.WriteField("preprocessing_options", string(preprocessing)) writer.WriteField("webhook_url", "http://webhook.musicgpt.com") writer.Close() req, _ := http.NewRequest("POST", "https://api.musicgpt.com/api/public/v1/Extraction", body) req.Header.Add("Authorization", "") req.Header.Add("Content-Type", writer.FormDataContentType()) client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() responseBody, _ := io.ReadAll(resp.Body) fmt.Println(string(responseBody)) } ``` -------------------------------- ### Search Voices by Name Source: https://docs.musicgpt.com/api-documentation/endpoint/searchVoices Search for voices to get their voice ID by their names using a query string. This endpoint allows filtering voices by name and paginating results. ```APIDOC ## GET /searchVoices ### Description Search for voices to get their voice ID by their names using a query string. This endpoint allows filtering voices by name and paginating results. ### Method GET ### Endpoint https://api.musicgpt.com/api/public/v1/searchVoices ### Parameters #### Query Parameters - **query** (string) - Required - The search string to filter voices by name - **limit** (integer) - Optional - Maximum number of voices per page (default: 20) - **page** (integer) - Optional - Page number for pagination (default: 0) ### Request Example ```json { "example": "" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **voices** (array) - An array of voice objects, each containing `voice_id` and `voice_name`. - **limit** (integer) - The limit of voices returned per page. - **page** (integer) - The current page number. - **total** (integer) - The total number of voices available. #### Response Example ```json { "success": true, "voices": [ { "voice_id": "JustinBieber", "voice_name": "Justin Bieber" } ], "limit": 20, "page": 0, "total": 2 } ``` #### Error Response (500) - **success** (boolean) - Indicates if the request was successful. - **error** (string) - A message describing the internal server error. #### Error Response Example ```json { "success": false, "error": "Internal Server Error" } ``` ``` -------------------------------- ### GET /byId Source: https://docs.musicgpt.com/api-documentation/endpoint/getById Retrieve details of a conversion using `task_id` or `conversion_id`. You must provide either `task_id` or `conversion_id`, but not both. The `conversionType` is a required enum specifying the type of conversion. ```APIDOC ## GET /byId ### Description Retrieve details of a conversion using `task_id` or `conversion_id`. You must provide either `task_id` or `conversion_id`, but not both. The `conversionType` is a required enum specifying the type of conversion. ### Method GET ### Endpoint https://api.musicgpt.com/api/public/v1/byId ### Parameters #### Query Parameters - **conversionType** (enum) - Required - The type of Conversion you want to get your details from. Possible values: MUSIC_AI, TEXT_TO_SPEECH, VOICE_CONVERSION, EXTRACTION, COVER, STEMS_SEPARATION, VOCAL_EXTRACTION, DENOISING, DEECHO, DEREVERB, SOUND_GENERATOR, AUDIO_TRANSCRIPTION, AUDIO_SPEED_CHANGER, AUDIO_MASTERING, AUDIO_CUTTER, REMIX, FILE_CONVERT, KEY_BPM_EXTRACTION, AUDIO_TO_MIDI, EXTEND, INPAINT, SING_OVER_INSTRUMENTAL, LYRICS_GENERATOR - **task_id** (string) - Optional - Task ID associated with the conversion. Note: You must provide either `task_id` or `conversion_id`, but not both. - **conversion_id** (string) - Optional - Conversion ID to fetch details. Note: You must provide either `task_id` or `conversion_id`, but not both. ### Request Example ```json { "example": "Not applicable for GET request" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **conversion** (object) - Contains the conversion details. - **task_id** (string) - The task ID of the conversion. - **conversion_id** (string) - The unique ID of the conversion. - **status** (string) - The current status of the conversion (e.g., COMPLETED). - **status_msg** (string) - A message describing the status. - **audio_url** (string) - URL to the converted audio file. - **conversion_cost** (number) - The cost associated with the conversion. - **title** (string) - The title of the conversion. - **lyrics** (string) - Lyrics associated with the conversion, if applicable. - **music_style** (string) - The music style of the conversion. - **createdAt** (string) - The date and time when the conversion was created (ISO 8601 format). - **updatedAt** (string) - The date and time when the conversion was last updated (ISO 8601 format). #### Response Example ```json { "success": true, "conversion": { "task_id": "12345678-abcd-1234-efgh-567890abcdef", "conversion_id": "87654321-dcba-4321-hgfe-098765fedcba", "status": "COMPLETED", "status_msg": "Conversion successful", "audio_url": "https://musicgpt.s3.amazonaws.com/audiofile.mp3", "conversion_cost": 1.25, "title": "Generated Song", "lyrics": "[Verse 1]...", "music_style": "Pop", "createdAt": "2025-01-01T12:00:00Z", "updatedAt": "2025-01-01T12:05:00Z" } } ``` #### Error Response (400) - **success** (boolean) - Indicates if the request was successful. - **message** (string) - A message describing the error. #### Error Response Example ```json { "success": false, "message": "Invalid request parameters" } ``` ``` -------------------------------- ### Extend Task API - Validation Error Example Source: https://docs.musicgpt.com/api-documentation/conversions/extend This example shows the JSON response for a validation error when using the extend task API. It indicates a failure status and provides a specific error message detailing the missing required parameters. ```json { "success": false, "error": "audio_file or audio_url and extend_after are required." } ``` -------------------------------- ### Sing Over Instrumental API Endpoint (Python) Source: https://docs.musicgpt.com/api-documentation/endpoint/sing_over_instrumental This Python code snippet demonstrates how to interact with the MusicGPT API's /sing_over_instrumental endpoint. It shows how to send a POST request with either an audio file or an audio URL, along with lyrics, prompt, and optional webhook URL. Ensure you replace '' with your actual API key. The example includes two options for providing the audio: using a URL or uploading a local file. ```yaml paths: path: /sing_over_instrumental method: post servers: - url: https://api.musicgpt.com/api/public/v1 description: Production server request: security: - title: ApiKeyAuth parameters: query: {} header: Authorization: type: apiKey cookie: {} parameters: path: {} query: {} header: {} cookie: {} body: multipart/form-data: schemaArray: - type: object properties: audio_file: allOf: - &ref_0 type: string format: binary description: Uploaded instrumental audio file. audio_url: allOf: - &ref_1 type: string description: URL or S3 path to the input instrumental audio. example: https://bucket.s3.amazonaws.com/audio.mp3 prompt: allOf: - &ref_2 type: string description: Description of the singing style, tone, or genre. example: Sing emotional vocals over a soft piano instrumental. lyrics: allOf: - &ref_3 type: string description: The lyrics to be sung over the instrumental. example: Never mind I'll find someone like you... maxLength: 2000 gender: allOf: - &ref_4 type: string description: Voice gender to guide generation. enum: - male - female - neutral example: female webhook_url: allOf: - &ref_5 type: string description: >- Callback URL to receive status updates or final audio result. example: https://yourdomain.com/webhook required: true requiredProperties: - prompt - lyrics - audio_url - type: object properties: audio_file: allOf: - *ref_0 audio_url: allOf: - *ref_1 prompt: allOf: - *ref_2 lyrics: allOf: - *ref_3 gender: allOf: - *ref_4 webhook_url: allOf: - *ref_5 required: true requiredProperties: - prompt - lyrics - audio_file examples: example: value: audio_url: https://bucket.s3.amazonaws.com/audio.mp3 prompt: Sing emotional vocals over a soft piano instrumental. lyrics: Never mind I'll find someone like you... gender: female webhook_url: https://yourdomain.com/webhook response: '200': application/json: schemaArray: - type: object properties: success: allOf: - type: boolean message: allOf: - type: string task_id: allOf: - type: string conversion_id_1: allOf: - type: string conversion_id_2: allOf: - type: string eta: allOf: - type: integer description: Estimated processing time in seconds credit_estimate: ``` ```Python import requests url = "https://api.musicgpt.com/api/public/v1/sing_over_instrumental" headers = {"Authorization": ""} data = { "prompt": "Sing emotional vocals over a soft piano instrumental.", "lyrics": "Never mind I'll find someone like you...", "gender": "female", "webhook_url": "https://yourdomain.com/webhook" } # Option 1: Use audio_url data["audio_url"] = "https://bucket.s3.amazonaws.com/audio.mp3" response = requests.post(url, headers=headers, data=data) # Option 2: Upload file # with open("audio.mp3", "rb") as f: # files = {"audio_file": f} # response = requests.post(url, headers=headers, data=data, files=files) # print(response.json()) ``` -------------------------------- ### Go HTTP POST Audio Mastering Request Source: https://docs.musicgpt.com/api-documentation/conversions/audiomastering This Go snippet shows how to make an audio mastering request to the MusicGPT API using the standard net/http package. It constructs a POST request with necessary headers and body, then prints the response. Ensure your API key is correctly inserted. ```go package main import ( "bytes" "fmt" "io" "net/http" "strings" ) func main() { url := "https://api.musicgpt.com/api/public/v1/audio_mastering" token := "<<>>" data := "audio_url=https://example.com/input_audio.mp3&reference_audio_url=https://example.com/reference_track.wav&output_extension=wav&webhook_url=http://your-webhook-url.com/callback" req, _ := http.NewRequest("POST", url, strings.NewReader(data)) req.Header.Add("Authorization", token) res, _ := http.DefaultClient.Do(req) defer res.Body.Close() body, _ := io.ReadAll(res.Body) fmt.Println(string(body)) ``` -------------------------------- ### Go HTTP POST Request for Audio Mastering Source: https://docs.musicgpt.com/api-documentation/endpoint/audio_mastering This Go snippet shows how to send a POST request to the audio mastering API. It constructs the request body, sets the authorization header, and prints the response. This is useful for integrating audio mastering into Go applications. ```go package main import ( "bytes" "fmt" "io" "net/http" "strings" ) func main() { url := "https://api.musicgpt.com/api/public/v1/audio_mastering" token := "<<>>" data := "audio_url=https://example.com/input_audio.mp3&reference_audio_url=https://example.com/reference_track.wav&output_extension=wav&webhook_url=http://your-webhook-url.com/callback" req, _ := http.NewRequest("POST", url, strings.NewReader(data)) req.Header.Add("Authorization", token) res, _ := http.DefaultClient.Do(req) defer res.Body.Close() body, _ := io.ReadAll(res.Body) fmt.Println(string(body)) } ``` -------------------------------- ### Transcription Source: https://docs.musicgpt.com/api-documentation/index Get accurate text transcription from speech. ```APIDOC ## POST /api/transcribe ### Description This endpoint transcribes spoken audio into text. ### Method POST ### Endpoint /api/transcribe ### Parameters #### Request Body - **audio_file** (file) - Required - The audio file to transcribe. - **language** (string) - Optional - The language of the audio (e.g., 'en-US'). ### Request Example ``` (Multipart form data with 'audio_file' and 'language') ``` ### Response #### Success Response (200) - **transcription** (string) - The transcribed text. - **job_id** (string) - The ID of the transcription job. #### Response Example ```json { "transcription": "This is the transcribed text from the audio file.", "job_id": "job_def456ghi" } ``` ``` -------------------------------- ### Search Voices by Name (OpenAPI Specification) Source: https://docs.musicgpt.com/api-documentation/endpoint/searchVoices This OpenAPI specification defines the GET /searchVoices endpoint for the MusicGPT API. It allows searching for voices by name using a query string and supports pagination. The response includes voice details, pagination information, and success/error status. ```yaml paths: path: /searchVoices method: get servers: - url: https://api.musicgpt.com/api/public/v1 description: Production server request: security: - title: ApiKeyAuth parameters: query: {} header: Authorization: type: apiKey cookie: {} parameters: path: {} query: query: schema: - type: string required: true description: The search string to filter voices by name limit: schema: - type: integer required: false description: Maximum number of voices per page default: 20 page: schema: - type: integer required: false description: Page number for pagination default: 0 header: {} cookie: {} body: {} response: '200': application/json: schemaArray: - type: object properties: success: allOf: - type: boolean voices: allOf: - type: array items: type: object properties: voice_id: type: string voice_name: type: string limit: allOf: - type: integer page: allOf: - type: integer total: allOf: - type: integer examples: example: value: success: true voices: - voice_id: JustinBieber voice_name: Justin Bieber limit: 20 page: 0 total: 2 description: Successful response '500': application/json: schemaArray: - type: object properties: success: allOf: - type: boolean error: allOf: - type: string examples: example: value: success: false error: Internal Server Error description: Internal Server Error deprecated: false type: path components: schemas: {} ``` -------------------------------- ### Initiate Inpaint Task Source: https://docs.musicgpt.com/api-documentation/conversions/inpaint Submits a request to initiate an inpainting task. This endpoint processes the request and returns task details including an estimated time of arrival and credit estimate. ```APIDOC ## POST /inpaint ### Description Initiates an inpainting task. The service will process the request and provide details about the task's progress and resource estimation. ### Method POST ### Endpoint /inpaint ### Parameters #### Request Body - **audio_file** (file) - Required - The audio file to be used for inpainting. - **audio_url** (string) - Required - URL of the audio file. - **replace_range** (array) - Required - Specifies the range within the audio to be replaced. Example: `[start_time, end_time]` ### Request Example ```json { "audio_file": "", "replace_range": [10.5, 25.2] } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **message** (string) - A message confirming the successful submission of the inpaint request. - **task_id** (string) - The unique identifier for the submitted task. - **conversion_id_1** (string) - Identifier for the first conversion process. - **conversion_id_2** (string) - Identifier for the second conversion process. - **eta** (integer) - Estimated processing time in seconds. - **credit_estimate** (number) - The estimated credit cost for the task. #### Response Example ```json { "success": true, "message": "Inpaint request submitted successfully", "task_id": "task-xyz-123", "conversion_id_1": "inpaint-abc", "conversion_id_2": "inpaint-def", "eta": 40, "credit_estimate": 45 } ``` #### Error Response (422) - **success** (boolean) - Indicates if the request was successful (will be false). - **error** (string) - A description of the validation error. #### Response Example ```json { "success": false, "error": "audio_file or audio_url and valid replace range are required." } ``` #### Error Response (500) - **success** (boolean) - Indicates if the request was successful (will be false). - **error** (string) - A message indicating an internal server error. #### Response Example ```json { "success": false, "error": "Internal Server Error" } ``` ```