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"
}
Get WAV File Duration
{
"mp3_url": "https://assets.jcaigc.cn/audio/music.wav"
}
Response Format
Success Response
{
"duration": 120000000
}
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"
}
}
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"
}
}
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
- mp3_url parameter: Required parameter, need to provide complete audio file URL
- File format: Although parameter name is mp3_url, it actually supports multiple audio formats
- File size: Recommended to control within reasonable range, large files may cause processing timeout
Usage Scenarios
-
Video Editing Preprocessing:
- Get audio duration before adding audio to video project
- Used for calculating reasonable segmentation of audio clips
-
Audio Material Management:
- Batch get duration information of files in audio library
- Used for classification and filtering of audio materials
-
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);
});
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")
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']}")
Related Interfaces
- add_audios - Batch add audio to CapCut draft
- add_videos - Batch add video to CapCut draft
- easy_create_material - Quickly create multimedia materials
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
Core Logic
- Parameter validation: Validate the validity of mp3_url parameter
- File download: Download audio file from URL to temporary directory
- FFprobe analysis: Use FFprobe tool to get precise audio metadata
- Duration extraction: Extract duration data from format info or stream info
- Resource cleanup: Clean up temporarily downloaded files
- 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)