POST
/
audio-separation-results
Get Audio Separation Runs Results
curl --request POST \
  --url https://client.camb.ai/apis/audio-separation-results \
  --header 'Content-Type: application/json' \
  --header 'x-api-key: <api-key>' \
  --data '{
  "run_ids": [
    12345,
    6789
  ]
}'
{
  "1001": {
    "foreground_audio_url": "https://example.com/audio-separation/1001/fg_audio.flac",
    "background_audio_url": "https://example.com/audio-separation/1001/bg_audio.flac"
  },
  "1002": {
    "foreground_audio_url": "https://example.com/audio-separation/1002/fg_audio.flac",
    "background_audio_url": "https://example.com/audio-separation/1002/bg_audio.flac"
  }
}

Accessing Multiple Separated Audio Collections

This endpoint enables you to retrieve the results from multiple completed audio separation tasks in a single, efficient request. Instead of making individual requests for each audio separation result, you can fetch foreground and background audio components from several processing runs simultaneously, streamlining your workflow when dealing with batch audio operations.

Each audio separation task produces two distinct audio tracks from your original recording: a foreground track containing primary audio elements (speech, vocals, or main instruments) and a background track with supporting elements (ambient sounds, musical accompaniment, or secondary audio). This bulk endpoint allows you to collect these separated components from multiple runs at once, making it ideal for applications processing audio libraries, podcast batches, or large-scale content analysis projects.

How Bulk Audio Separation Retrieval Works

The bulk retrieval system operates on a simple principle: you provide an array of run IDs corresponding to your completed audio separation tasks, and the system returns organized results for each requested separation. This approach offers significant advantages over individual retrieval requests:

Efficiency Benefits:

  • Reduces network overhead by consolidating multiple requests into one
  • Minimizes latency when retrieving results from several audio separation tasks
  • Simplifies client-side code for handling multiple audio file collections
  • Provides better performance for batch audio processing workflows

Practical Applications:

  • Processing results from multiple podcast episodes or music tracks
  • Building audio libraries with separated components
  • Batch operations for content creators working with multiple recordings
  • Automated workflows that separate audio from video content in bulk

Request Format

The endpoint expects a JSON payload containing an array of run IDs that identify the audio separation tasks you want to retrieve results for:

{
  "run_ids": [
    "12345",
    "45678",
    "112233"
  ]
}

Each run ID should correspond to a previously initiated audio separation task. The system processes all provided run IDs and returns results for those that have completed successfully.

Response Structure

The response contains an array of results, where each item corresponds to one of the requested run IDs. For successful separations, each result includes both foreground and background audio URLs:

  [
    12345: {
      "foreground_audio_url": "https://storage.example.com/audio/12345_foreground.wav",
      "background_audio_url": "https://storage.example.com/audio/12345_background.wav"
    },
    45678: {
      "foreground_audio_url": "https://storage.example.com/audio/45678_foreground.wav",
      "background_audio_url": "https://storage.example.com/audio/45678_background.wav"
    }
  ]

Understanding the Response Fields:

  • run_id: The original run ID you provided in the request
  • status: Current status of the separation task (completed, failed, processing)
  • foreground_audio_url: Direct download URL for the isolated foreground audio components
  • background_audio_url: Direct download URL for the isolated background audio components
  • error: Error message explaining why a separation task failed (only present for failed tasks)

Understanding Separated Audio Components

Each successful audio separation produces two complementary audio files that work together to reconstruct your original recording:

Foreground Audio Components:

  • Contain dominant audio elements like vocals, speech, or lead instruments
  • Represent the primary focus of the recording
  • Ideal for creating karaoke tracks, enhancing speech clarity, or isolating musical performances
  • Typically contain the most prominent frequency ranges and temporal patterns

Background Audio Components:

  • Contain ambient sounds, musical accompaniment, or secondary audio elements
  • Provide context and support to the foreground elements
  • Perfect for creating instrumental tracks, ambient soundscapes, or removing unwanted background noise
  • Include the supporting audio texture that gives recordings their full character

Organizing Separated Audio Collections

import requests
import os
from typing import List, Dict, Optional


def download_audio(url: str, filepath: str) -> bool:
    """
    Download audio file from URL to specified filepath
    """
    try:
        response = requests.get(url, stream=True)
        response.raise_for_status()

        with open(filepath, "wb") as f:
            for chunk in response.iter_content(chunk_size=8192):
                f.write(chunk)

        print(f"Downloaded: {filepath}")
        return True
    except requests.exceptions.RequestException as e:
        print(f"Failed to download {url}: {e}")
        return False


def organize_separation_results(run_ids: List[int], output_dir: str) -> Optional[Dict]:
    """
    Retrieve and organize multiple audio separation results
    Args:
        run_ids: List of run IDs to fetch results for
        output_dir: Directory to save organized results
    Returns:
        Dictionary containing organized results or None if request fails
    """
    try:
        # Make API request
        response = requests.post(
            "https://client.camb.ai/apis/audio-separation-results",
            headers={"x-api-key": "YOUR_API_KEY_HERE", "Content-Type": "application/json"},
            json={"run_ids": run_ids},
        )
        response.raise_for_status()
        results = response.json()

        # Create main output directory
        os.makedirs(output_dir, exist_ok=True)

        organized_results = {}

        # Process each result (key is run_id as string, value is the result data)
        for run_id_str, result_data in results.items():
            run_id = int(run_id_str)

            # Create directory for this separation
            run_dir = os.path.join(output_dir, f"run_{run_id}")
            os.makedirs(run_dir, exist_ok=True)

            # Download foreground audio
            foreground_url = result_data["foreground_audio_url"]
            foreground_path = os.path.join(run_dir, "foreground.flac")
            foreground_success = download_audio(foreground_url, foreground_path)

            # Download background audio
            background_url = result_data["background_audio_url"]
            background_path = os.path.join(run_dir, "background.flac")
            background_success = download_audio(background_url, background_path)

            # Store organized result info
            organized_results[run_id] = {
                "directory": run_dir,
                "foreground_url": foreground_url,
                "background_url": background_url,
                "foreground_path": foreground_path if foreground_success else None,
                "background_path": background_path if background_success else None,
                "download_success": foreground_success and background_success,
            }

            status = "βœ“" if organized_results[run_id]["download_success"] else "βœ—"
            print(f"{status} Organized separation results for run_id {run_id}")

        print(f"\nProcessed {len(organized_results)} separation results")
        print(f"Results saved to: {output_dir}")

        return organized_results

    except requests.exceptions.HTTPError as e:
        print(f"HTTP Error {e.response.status_code}: {e.response.text}")
        return None
    except requests.exceptions.RequestException as e:
        print(f"Request failed: {e}")
        return None
    except Exception as e:
        print(f"Unexpected error: {e}")
        return None


def print_summary(organized_results: Dict) -> None:
    """
    Print a summary of organized results
    """
    print("\n" + "=" * 50)
    print("AUDIO SEPARATION RESULTS SUMMARY")
    print("=" * 50)

    successful_downloads = 0
    failed_downloads = 0

    for run_id, result in organized_results.items():
        status = "SUCCESS" if result["download_success"] else "FAILED"
        print(f"Run ID {run_id}: {status}")
        print(f"  Directory: {result['directory']}")

        if result["download_success"]:
            successful_downloads += 1
            print(f"  Foreground: {result['foreground_path']}")
            print(f"  Background: {result['background_path']}")
        else:
            failed_downloads += 1
            print("Download failed for one or both audio files")
        print()

    print(f"Total: {len(organized_results)} results")
    print(f"Successful: {successful_downloads}")
    print(f"Failed: {failed_downloads}")


# Example usage
if __name__ == "__main__":
    # Example run IDs from your response
    run_ids_to_process = [112233, 456789]
    output_directory = "./audio_separation_results"

    # Organize the results
    results = organize_separation_results(run_ids_to_process, output_directory)

    if results:
        print_summary(results)

        # Example: Get all foreground audio paths for further processing
        foreground_paths = [
            result["foreground_path"]
            for result in results.values()
            if result["foreground_path"]
        ]

        if foreground_paths:
            print("\nForeground audio files ready for processing:")
            for path in foreground_paths:
                print(f"  - {path}")

Status Management and Error Handling

When working with bulk audio separation results, individual tasks within your batch may have different statuses. The endpoint returns results for all requested run IDs, but some may not be ready yet or may have encountered processing errors.

Common Status Scenarios:

  • Mixed Status Results: Some separations completed while others are still processing
  • Invalid Run IDs: Non-existent run IDs will be marked with appropriate error status
  • Processing Failures: Some audio files may fail separation due to format issues or processing errors
  • Expired URLs: Older completed separations may have expired download URLs

Best Practices for Status Management:

  1. Always check the status field before attempting to download audio files
  2. Implement retry logic for tasks that are still processing
  3. Handle failed separations gracefully with appropriate user feedback
  4. Store successful results promptly as download URLs may expire
  5. Log processing errors for debugging and quality improvement

Audio Processing Workflow Integration

This bulk endpoint integrates seamlessly into larger audio processing workflows. Consider this typical pattern for handling multiple audio files:

  1. Submit Multiple Separations: Upload several audio files for separation processing
  2. Collect Run IDs: Store all returned run IDs from your separation requests
  3. Batch Status Checking: Use this bulk endpoint to check the status of multiple separations simultaneously
  4. Process Completed Separations: Download and organize foreground and background audio files
  5. Handle Incomplete Tasks: Retry processing for failed separations or wait for still-processing tasks

This workflow is particularly effective for:

  • Podcast Production: Separating speech from background music across multiple episodes
  • Music Production: Isolating vocals and instruments from multiple tracks
  • Content Analysis: Processing large audio libraries for machine learning or analysis
  • Accessibility Enhancement: Creating separate audio tracks for improved accessibility

Technical Considerations

Audio Format and Quality: The separated audio files are typically delivered in high-quality formats suitable for professional audio editing. Both foreground and background components maintain the original audio quality while providing clean separation between different audio elements.

File Size and Storage: Since each original audio file produces two separate output files (foreground and background), consider storage requirements when processing large batches. The combined size of separated files will be larger than the original due to the dual-track output.

Download URL Expiration: The presigned URLs returned in the response are temporary and will expire after a certain period. Implement prompt download and storage strategies to ensure you don’t lose access to your separated audio files.

Processing Time Considerations: Audio separation is a computationally intensive process. When submitting multiple files, processing times can vary based on audio length, complexity, and current system load. The bulk results endpoint helps you efficiently monitor multiple separations without overwhelming the system with frequent individual status checks.

Quality Optimization: The effectiveness of audio separation depends on the characteristics of your original audio. Files with clear distinction between foreground and background elements (like speech over music) typically produce better separation results than complex multi-layered audio with overlapping frequency ranges.

By leveraging this bulk audio separation results endpoint, you can build sophisticated audio processing applications that handle multiple separations efficiently, enabling creative workflows that scale with your audio production needs while maintaining professional quality standards.

Authorizations

x-api-key
string
header
required

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.

Body

application/json

Response

200
application/json

Successful Response

An object containing the results of one to five audio separation runs. Each key in the object is a unique identifier for a run, and the corresponding value is the files URLs generated by the audio separation process.