> ## Documentation Index
> Fetch the complete documentation index at: https://docs.camb.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Create Audio Separation

> Creates a task to separate an audio file into distinct background and foreground components

Transform your mixed content into clean, isolated components with our powerful audio separation system. This innovative endpoint enables you to extract distinct foreground elements (such as vocals or lead instruments) from background elements (like accompaniment or ambient sounds). Whether you're producing music, cleaning up recordings, creating remixes, or developing audio-focused applications, this capability allows you to deconstruct complex media files into their fundamental components for enhanced control and creative flexibility.

<Tip>For optimal separation quality, we recommend using media files with minimal compression and clear distinction between foreground and background elements. Higher quality input files generally produce better separation results.</Tip>

## The Audio Separation Process

When you submit an audio separation request, our system begins a sophisticated workflow:

<Steps>
  <Step title="Task Creation">
    The system registers your request and establishes a dedicated processing task, returning a unique task identifier (`task_id`) that you'll use to track and retrieve your separated audio components.
  </Step>

  <Step title="Audio Analysis">
    Our advanced audio processing algorithms analyze the spectral and temporal characteristics of your audio file, identifying patterns that distinguish foreground from background elements.
  </Step>

  <Step title="Component Separation">
    Using specialized neural networks, the system carefully separates the audio into distinct foreground and background stems while preserving the acoustic quality of each component.
  </Step>
</Steps>

Throughout this process, you can monitor the status of your separation task by polling the [`/audio-separation/{task_id}`](get-audio-separation-status) endpoint with the `task_id` provided in your initial response.

## Creating Your First Audio Separation Request

Let's examine how to initiate an audio separation task using Python:

```python [expandable] theme={null}
import requests

# Your API authentication
headers = {
    "x-api-key": "your-api-key",  # Replace with your actual API key
}

def create_audio_separation(media_file_path):
    """
    Submits a new audio separation task and returns the task ID for tracking.

    Parameters:
    - media_file_path: Path to the audio file you want to separate
    """
    try:
        # Prepare the multipart form data with the audio file
        files = {
            "media_file": (media_file_path.split('/')[-1], open(media_file_path, "rb"))
        }

        # Submit the separation request
        response = requests.post(
            "https://client.camb.ai/apis/audio-separation",
            headers=headers,
            files=files
        )

        # Verify the request was successful
        response.raise_for_status()

        # Extract the task ID from the response
        result = response.json()
        task_id = result.get("task_id")

        print(f"Audio separation task submitted successfully! Task ID: {task_id}")
        return task_id

    except requests.exceptions.RequestException as e:
        print(f"Error submitting audio separation task: {e}")
        if hasattr(e, 'response') and e.response is not None:
            print(f"Response content: {e.response.text}")
        return None

# Example usage
audio_path = "path/to/your/audio/file.mp3"
task_id = create_audio_separation(audio_path)
```

## Monitoring Your Separation Progress

After submission, your audio separation task enters our processing pipeline. You can monitor the progress by polling the status endpoint:

```python [expandable] theme={null}
def check_separation_status(task_id):
    """
    Checks the status of an audio separation task.
    Returns the current status and any available result information.

    Parameters:
    - task_id: The ID of the separation task to check
    """
    if not task_id:
        print("No task ID provided.")
        return None

    try:
        response = requests.get(
            f"https://client.camb.ai/apis/audio-separation/{task_id}",
            headers=headers
        )

        # Verify the request was successful
        response.raise_for_status()

        # Parse the status information
        status_data = response.json()
        print(f"Current status: {status_data['status']}")

        # If the separation is complete, display the results
        if status_data['status'] == "SUCCESS":
            print("Audio separation completed successfully!")
            print(f"Foreground audio URL: {status_data.get('foreground_url')}")
            print(f"Background audio URL: {status_data.get('background_url')}")

        return status_data

    except requests.exceptions.RequestException as e:
        print(f"Error checking separation status: {e}")
        return None

# Check the status of your separation task
status_info = check_separation_status(task_id)
```

## Supported Audio Formats

Our audio separation system supports a variety of common audio formats to accommodate your workflow needs:

* **FLAC** (Free Lossless Audio Codec) - Ideal for high-quality lossless audio
* **MP3** (MPEG Audio Layer III) - Common compressed format widely supported across platforms
* **WAV** (Waveform Audio File Format) - Uncompressed audio format with excellent quality
* **AAC** (Advanced Audio Coding) - High-quality compressed format commonly used in mobile devices

## Best Practices for Audio Separation

To achieve the highest quality separation results, consider these professional recommendations:

1. **Use High-Quality Sources**: Whenever possible, use uncompressed (WAV) or lossless (FLAC) audio for separation.

2. **Optimal Length**: While the system can handle various durations, files between 10 seconds and 10 minutes typically yield the best results.

3. **Clear Recording**: Audio with minimal background noise, distortion, or heavy effects will separate more cleanly.

4. **Balanced Mix**: Ensure that both foreground and background elements are audible in the original mix for best separation.

5. **Consider Preprocessing**: For challenging audio, consider using noise reduction or equalization before submission to improve separation quality.


## OpenAPI

````yaml post /audio-separation
openapi: 3.1.0
info:
  title: FastAPI
  version: 0.1.0
servers:
  - url: https://client.camb.ai/apis
security: []
paths:
  /audio-separation:
    post:
      tags:
        - Apis
        - Audio-Separation
      summary: Create Audio Separation
      operationId: create_audio_separation_audio_separation_post
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              $ref: '#/components/schemas/CreateAudioSeparationRequestPayload'
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TaskID'
                description: >-
                  A JSON that contains unique identifier for the task. This is
                  used to query the status of the audio separation task that is
                  running. It is returned when a create request is made to
                  separate audio into background and foreground.
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
      security:
        - APIKeyHeader: []
components:
  schemas:
    CreateAudioSeparationRequestPayload:
      allOf:
        - $ref: '#/components/schemas/CreateTaskWithNameAndDescription'
        - properties:
            media_file:
              type: string
              format: binary
              title: Media File
              description: >-
                Media file to processed. AAC, FLAC, MP3 and WAV formats are
                supported.
              required: true
          type: object
      title: CreateAudioSeparationRequestPayload
    TaskID:
      properties:
        task_id:
          type: string
          title: Task ID
      type: object
      title: Task ID
    HTTPValidationError:
      properties:
        detail:
          items:
            $ref: '#/components/schemas/ValidationError'
          type: array
          title: Detail
      type: object
      title: HTTPValidationError
    CreateTaskWithNameAndDescription:
      properties:
        project_name:
          type: string
          title: Project Name
          description: >-
            Enter a distinctive name for your project that reflects its purpose
            or content. This name will be displayed in your CAMB.AI workspace
            dashboard and used to organize related assets, transcriptions, etc..
            . Choose something memorable that helps you quickly identify this
            specific project among your other voice, audio and localization
            tasks.
          minLength: 3
          maxLength: 255
          nullable: true
        project_description:
          type: string
          title: Project Description
          description: >-
            Provide details about your project's goals and specifications.
            Include information such as the target languages for translation or
            dubbing, desired voice characteristics, emotional tones to capture,
            or specific audio processing requirements, outlining the workflow
            here can serve as valuable documentation for organizational
            purposes.
          minLength: 3
          maxLength: 5000
          nullable: true
    ValidationError:
      properties:
        loc:
          items:
            anyOf:
              - type: string
              - type: integer
          type: array
          title: Location
        msg:
          type: string
          title: Message
        type:
          type: string
          title: Error Type
      type: object
      required:
        - loc
        - msg
        - type
      title: ValidationError
  securitySchemes:
    APIKeyHeader:
      type: apiKey
      in: header
      name: x-api-key
      description: >-
        The `x-api-key` is a custom header required for authenticating requests
        to our API. Include this header in your request with the appropriate API
        key value to securely access our endpoints. You can find your API key(s)
        in the 'API' section of our studio website.

````