DEV Community

Hommy
Hommy

Posted on

[JCAIGC]Get the duration of audio files

get_audio_duration API Documentation

API Overview

API Name: get_audio_duration

API Endpoint: POST /openapi/capcut-mate/v1/get_audio_duration

Function Description: Get the duration of audio files, supporting various common audio formats. Uses FFprobe tool for precise audio analysis, returning the accurate duration of audio files in microseconds.

More Documentation

πŸ“– For more detailed documentation and tutorials, please visit: https://docs.jcaigc.cn

Request Parameters

Request Body (application/json)

Parameter Type Required Default Description
mp3_url string Yes - Audio file URL, supports common audio formats like mp3

Parameter Description

  • mp3_url: Complete URL address of the audio file
    • Supported formats: mp3, wav, aac, flac and other common audio formats
    • Need to ensure URL is accessible and file is complete
    • Recommended file size not exceeding 100MB

Request Examples

Get MP3 File Duration

{
  "mp3_url": "https://assets.jcaigc.cn/audio/sample.mp3"
}
Enter fullscreen mode Exit fullscreen mode

Get WAV File Duration

{
  "mp3_url": "https://assets.jcaigc.cn/audio/music.wav"
}
Enter fullscreen mode Exit fullscreen mode

Response Format

Success Response

{
  "duration": 120000000
}
Enter fullscreen mode Exit fullscreen mode

Response Field Description

Field Type Description
duration integer Audio duration, unit: microseconds. Example: 120000000 represents 120 seconds (2 minutes)

Duration Unit Conversion

  • Microseconds to seconds: duration Γ· 1,000,000
  • Microseconds to milliseconds: duration Γ· 1,000
  • Examples:
    • 120000000 microseconds = 120 seconds = 2 minutes
    • 30000000 microseconds = 30 seconds
    • 5000000 microseconds = 5 seconds

Error Response

400 Bad Request - Parameter Validation Failed

{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Request parameter validation failed",
    "details": "mp3_url parameter cannot be empty"
  }
}
Enter fullscreen mode Exit fullscreen mode

500 Internal Server Error - Failed to Get Audio Duration

{
  "error": {
    "code": "AUDIO_DURATION_GET_FAILED",
    "message": "Failed to get audio duration",
    "details": "Failed to download audio file or unsupported file format"
  }
}
Enter fullscreen mode Exit fullscreen mode

Error Code Description

Error Code HTTP Status Code Description Solution
VALIDATION_ERROR 400 Request parameter validation failed Check if mp3_url parameter is correctly provided
AUDIO_DURATION_GET_FAILED 500 Failed to get audio duration Check if audio URL is accessible and file format is supported

Usage Instructions

Parameter Requirements

  1. mp3_url parameter: Required parameter, need to provide complete audio file URL
  2. File format: Although parameter name is mp3_url, it actually supports multiple audio formats
  3. File size: Recommended to control within reasonable range, large files may cause processing timeout

Usage Scenarios

  1. Video Editing Preprocessing:

    • Get audio duration before adding audio to video project
    • Used for calculating reasonable segmentation of audio clips
  2. Audio Material Management:

    • Batch get duration information of files in audio library
    • Used for classification and filtering of audio materials
  3. Synchronization Processing:

    • Ensure audio and video duration match
    • Calculate duration of audio fade-in and fade-out effects

Technical Description

  • Duration calculation: Uses FFprobe tool for precise audio analysis
  • Accuracy: Returned duration is high-precision actual value, supports 6 decimal places precision
  • Performance: Interface will download audio file for analysis, processing time depends on file size and network speed

Example Code

JavaScript Example

// Get audio duration
const getAudioDuration = async (audioUrl) => {
  const response = await fetch('/openapi/capcut-mate/v1/get_audio_duration', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      mp3_url: audioUrl
    })
  });

  const result = await response.json();

  if (response.ok) {
    const durationSeconds = result.duration / 1000000;
    console.log(`Audio duration: ${durationSeconds}seconds`);
    return result.duration;
  } else {
    console.error('Failed to get audio duration:', result.error);
    throw new Error(result.error.message);
  }
};

// Usage example
getAudioDuration('https://assets.jcaigc.cn/audio/sample.mp3')
  .then(duration => {
    console.log(`Audio duration (microseconds): ${duration}`);
    console.log(`Audio duration (seconds): ${duration / 1000000}`);
  })
  .catch(error => {
    console.error('Error:', error.message);
  });
Enter fullscreen mode Exit fullscreen mode

Python Example

import requests

def get_audio_duration(mp3_url):
    """Get audio file duration"""
    url = 'https://capcut-mate.jcaigc.cn/openapi/capcut-mate/v1/get_audio_duration'
    data = {
        'mp3_url': mp3_url
    }

    response = requests.post(url, json=data)
    if response.status_code == 200:
        result = response.json()
        duration_microseconds = result['duration']
        duration_seconds = duration_microseconds / 1_000_000
        return duration_microseconds, duration_seconds
    else:
        print(f"Request failed: {response.status_code}")
        print(response.json())
        return None

# Usage example
audio_url = "https://assets.jcaigc.cn/audio/sample.mp3"
duration_info = get_audio_duration(audio_url)

if duration_info:
    duration_microseconds, duration_seconds = duration_info
    print(f"Audio duration: {duration_seconds:.2f}seconds ({duration_microseconds}microseconds)")

    # Duration formatting
    minutes = int(duration_seconds // 60)
    seconds = int(duration_seconds % 60)
    print(f"Formatted duration: {minutes}minutes{seconds}seconds")
Enter fullscreen mode Exit fullscreen mode

Batch Processing Example

import requests
import json
from concurrent.futures import ThreadPoolExecutor
import time

def get_audio_duration_batch(audio_urls):
    """Batch get audio duration"""
    def get_single_duration(url):
        try:
            response = requests.post(
                'http://localhost:8000/v1/get_audio_duration',
                json={'mp3_url': url},
                timeout=30
            )
            if response.status_code == 200:
                duration = response.json()['duration']
                return {'url': url, 'duration': duration, 'success': True}
            else:
                return {'url': url, 'error': response.json(), 'success': False}
        except Exception as e:
            return {'url': url, 'error': str(e), 'success': False}

    # Concurrent processing
    with ThreadPoolExecutor(max_workers=5) as executor:
        results = list(executor.map(get_single_duration, audio_urls))

    return results

# Usage example
audio_urls = [
    "https://assets.jcaigc.cn/audio1.mp3",
    "https://assets.jcaigc.cn/audio2.wav",
    "https://assets.jcaigc.cn/audio3.aac"
]

results = get_audio_duration_batch(audio_urls)

for result in results:
    if result['success']:
        duration_seconds = result['duration'] / 1_000_000
        print(f"βœ“ {result['url']}: {duration_seconds:.2f}seconds")
    else:
        print(f"βœ— {result['url']}: {result['error']}")
Enter fullscreen mode Exit fullscreen mode

Related Interfaces

Technical Implementation

File Structure

src/
β”œβ”€β”€ schemas/get_audio_duration.py    # Request/response data models
β”œβ”€β”€ service/get_audio_duration.py    # Business logic implementation
└── router/v1.py                     # API route definition
Enter fullscreen mode Exit fullscreen mode

Core Logic

  1. Parameter validation: Validate the validity of mp3_url parameter
  2. File download: Download audio file from URL to temporary directory
  3. FFprobe analysis: Use FFprobe tool to get precise audio metadata
  4. Duration extraction: Extract duration data from format info or stream info
  5. Resource cleanup: Clean up temporarily downloaded files
  6. Response return: Return API response in compliance with specifications

Current Implementation Features

  • Uses FFprobe tool from FFmpeg project for audio analysis
  • Supports multiple audio formats (MP3, WAV, AAC, FLAC, etc.)
  • Provides high-precision duration data (microsecond level)
  • Complete error handling and resource cleanup mechanism
  • Supports timeout control to prevent long-term blocking

Advantages Description

Compared to the previous estimation method based on file size, the new FFprobe implementation provides:

  • Higher accuracy: Directly read duration from audio metadata
  • Wider support: Supports all audio formats that FFprobe can recognize
  • More reliable results: Does not rely on bitrate estimation, directly reads actual data

Version Information: v1.0

Last Updated: 2024-09-24


πŸ“š Project Resources

GitHub: https://github.com/Hommy-master/capcut-mate

Gitee: https://gitee.com/taohongmin-gitee/capcut-mate

Top comments (0)