Extract engaging snippets from audio files programmatically
hsa_)Send a POST request to:
https://www.harmonysnippetsai.com/api/v1/extract-snippet
Headers:
X-API-Key: your_api_key_here
Content-Type: multipart/form-data
Body:
file: your audio file (MP3 or WAV)You'll receive a JSON response containing the engaging snippet in base64 format. You can decode and play it.
The server may return non-JSON responses for errors. Always implement proper error handling:
Use these snippets to integrate HarmonySnippetsAI with your stack:
const fs = require('fs');
const FormData = require('form-data');
const axios = require('axios');
async function extractSnippet(audioFilePath, apiKey) {
// Check if file exists
if (!fs.existsSync(audioFilePath)) {
console.log(`❌ Error: File '${audioFilePath}' not found`);
return null;
}
const form = new FormData();
form.append('file', fs.createReadStream(audioFilePath));
try {
console.log(`🔄 Uploading ${audioFilePath}...`);
const response = await axios.post('https://www.harmonysnippetsai.com/api/v1/extract-snippet', form, {
headers: {
'X-API-Key': apiKey,
...form.getHeaders()
},
timeout: 30000
});
console.log(`📡 Response status: ${response.status}`);
console.log(`📋 Response headers:`, response.headers);
if (response.status === 200) {
if (response.data.success) {
// Decode base64 audio and save
const audioBuffer = Buffer.from(response.data.data.snippet_base64, 'base64');
fs.writeFileSync('snippet.wav', audioBuffer);
console.log('✅ Snippet saved as snippet.wav!');
return response.data;
} else {
console.log(`❌ API Error: ${response.data.error || 'Unknown error'}`);
return null;
}
} else {
console.log(`❌ HTTP Error ${response.status}`);
// Try to parse JSON error message
if (response.data && typeof response.data === 'object') {
console.log(`❌ Error: ${response.data.error || 'Unknown error'}`);
} else {
console.log(`📄 Response content: ${JSON.stringify(response.data).substring(0, 500)}...`);
}
return null;
}
} catch (error) {
if (error.code === 'ECONNABORTED') {
console.log('❌ Error: Request timed out');
} else if (error.code === 'ECONNREFUSED') {
console.log('❌ Error: Connection failed');
} else if (error.response) {
console.log(`❌ HTTP Error ${error.response.status}`);
// Handle non-JSON error responses
try {
const errorData = error.response.data;
if (typeof errorData === 'object') {
console.log(`❌ Error: ${errorData.error || 'Unknown error'}`);
} else {
console.log(`📄 Response content: ${errorData.substring(0, 500)}...`);
}
} catch (parseError) {
console.log(`📄 Response content: ${error.response.data}`);
}
} else {
console.log(`❌ Unexpected error: ${error.message}`);
}
return null;
}
}
// Usage
extractSnippet('song.mp3', 'hsa_your_api_key_here');
import requests
import base64
import mimetypes
import os
def extract_snippet(audio_file_path, api_key):
url = 'https://www.harmonysnippetsai.com/api/v1/extract-snippet'
# Check if file exists
if not os.path.exists(audio_file_path):
print(f"❌ Error: File '{audio_file_path}' not found")
return None
# Detect MIME type
mime_type, _ = mimetypes.guess_type(audio_file_path)
if not mime_type:
ext = os.path.splitext(audio_file_path)[1].lower()
mime_type = 'audio/mpeg' if ext == '.mp3' else 'audio/wav'
try:
with open(audio_file_path, 'rb') as file:
files = {
'file': (
os.path.basename(audio_file_path),
file,
mime_type
)
}
headers = {'X-API-Key': api_key}
print(f"🔄 Uploading {audio_file_path}...")
response = requests.post(url, files=files, headers=headers, timeout=30)
print(f"📡 Response status: {response.status_code}")
print(f"📋 Response headers: {dict(response.headers)}")
if response.status_code == 200:
try:
data = response.json()
if data.get('success'):
# Save snippet
audio_data = base64.b64decode(data['data']['snippet_base64'])
with open('snippet.wav', 'wb') as f:
f.write(audio_data)
print('✅ Snippet saved as snippet.wav!')
return data
else:
print(f"❌ API Error: {data.get('error', 'Unknown error')}")
return None
except requests.exceptions.JSONDecodeError:
print("❌ Error: Server returned non-JSON response")
print(f"📄 Response content: {response.text[:500]}...")
return None
else:
print(f"❌ HTTP Error {response.status_code}")
try:
# Try to parse JSON error message
error_data = response.json()
print(f"❌ Error: {error_data.get('error', 'Unknown error')}")
except requests.exceptions.JSONDecodeError:
# If response isn't JSON, show raw content
print(f"📄 Response content: {response.text[:500]}...")
return None
except FileNotFoundError:
print(f"❌ Error: File '{audio_file_path}' not found")
return None
except requests.exceptions.Timeout:
print("❌ Error: Request timed out")
return None
except requests.exceptions.ConnectionError:
print("❌ Error: Connection failed")
return None
except Exception as e:
print(f"❌ Unexpected error: {str(e)}")
return None
# Usage
if __name__ == "__main__":
result = extract_snippet('song.mp3', 'hsa_your_api_key_here')
if result:
print("🎵 Success! Check snippet.wav")
else:
print("💔 Failed to extract snippet")
#!/bin/bash
# Function to extract snippet with proper error handling
extract_snippet() {
local audio_file="$1"
local api_key="$2"
# Check if file exists
if [ ! -f "$audio_file" ]; then
echo "❌ Error: File '$audio_file' not found"
return 1
fi
echo "🔄 Uploading $audio_file..."
# Make request and capture both response and HTTP status
response=$(curl -s -w "HTTPSTATUS:%{http_code}" \
-X POST "https://www.harmonysnippetsai.com/api/v1/extract-snippet" \
-H "X-API-Key: $api_key" \
-F "file=@$audio_file" \
--connect-timeout 30 \
--max-time 120)
# Extract HTTP status and body
http_status=$(echo "$response" | grep -o "HTTPSTATUS:[0-9]*" | cut -d: -f2)
body=$(echo "$response" | sed 's/HTTPSTATUS:[0-9]*$//')
echo "📡 Response status: $http_status"
if [ "$http_status" -eq 200 ]; then
# Check if response is valid JSON and has success field
if echo "$body" | jq -e '.success' > /dev/null 2>&1; then
success=$(echo "$body" | jq -r '.success')
if [ "$success" = "true" ]; then
# Extract and decode base64 audio
echo "$body" | jq -r '.data.snippet_base64' | base64 -d > snippet.wav
echo "✅ Snippet saved as snippet.wav!"
return 0
else
error_msg=$(echo "$body" | jq -r '.error // "Unknown error"')
echo "❌ API Error: $error_msg"
return 1
fi
else
echo "❌ Error: Server returned non-JSON response"
echo "📄 Response content: ${body:0:500}..."
return 1
fi
else
echo "❌ HTTP Error $http_status"
# Try to parse JSON error message
if echo "$body" | jq -e '.error' > /dev/null 2>&1; then
error_msg=$(echo "$body" | jq -r '.error')
echo "❌ Error: $error_msg"
else
echo "📄 Response content: ${body:0:500}..."
fi
return 1
fi
}
# Usage
extract_snippet "song.mp3" "hsa_your_api_key_here"
import Foundation
func extractSnippet(audioURL: URL, apiKey: String, completion: @escaping (Bool, String?) -> Void) {
// Check if file exists
guard FileManager.default.fileExists(atPath: audioURL.path) else {
completion(false, "File not found: \(audioURL.path)")
return
}
let url = URL(string: "https://www.harmonysnippetsai.com/api/v1/extract-snippet")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue(apiKey, forHTTPHeaderField: "X-API-Key")
request.timeoutInterval = 30
let boundary = UUID().uuidString
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
var body = Data()
body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"file\"; filename=\"\(audioURL.lastPathComponent)\"\r\n".data(using: .utf8)!)
body.append("Content-Type: audio/mpeg\r\n\r\n".data(using: .utf8)!)
do {
body.append(try Data(contentsOf: audioURL))
} catch {
completion(false, "Failed to read audio file: \(error.localizedDescription)")
return
}
body.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)
request.httpBody = body
print("🔄 Uploading \(audioURL.lastPathComponent)...")
URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
if error.localizedDescription.contains("timed out") {
completion(false, "Request timed out")
} else {
completion(false, "Connection error: \(error.localizedDescription)")
}
return
}
guard let httpResponse = response as? HTTPURLResponse else {
completion(false, "Invalid response")
return
}
print("📡 Response status: \(httpResponse.statusCode)")
guard let data = data else {
completion(false, "No data received")
return
}
if httpResponse.statusCode == 200 {
do {
let json = try JSONSerialization.jsonObject(with: data) as? [String: Any]
if let success = json?["success"] as? Bool, success,
let responseData = json?["data"] as? [String: Any],
let base64Audio = responseData["snippet_base64"] as? String,
let audioData = Data(base64Encoded: base64Audio) {
// Save to Documents folder
let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileURL = documentsPath.appendingPathComponent("snippet.wav")
do {
try audioData.write(to: fileURL)
print("✅ Snippet saved to \(fileURL)")
completion(true, "Snippet saved successfully")
} catch {
completion(false, "Failed to save snippet: \(error.localizedDescription)")
}
} else {
let errorMsg = json?["error"] as? String ?? "Unknown error"
completion(false, "API Error: \(errorMsg)")
}
} catch {
// Handle non-JSON response
let responseString = String(data: data, encoding: .utf8) ?? "Unknown response"
print("❌ Error: Server returned non-JSON response")
print("📄 Response content: \(String(responseString.prefix(500)))...")
completion(false, "Server returned non-JSON response")
}
} else {
// Handle HTTP errors
do {
let json = try JSONSerialization.jsonObject(with: data) as? [String: Any]
let errorMsg = json?["error"] as? String ?? "HTTP Error \(httpResponse.statusCode)"
completion(false, errorMsg)
} catch {
let responseString = String(data: data, encoding: .utf8) ?? "Unknown response"
print("📄 Response content: \(String(responseString.prefix(500)))...")
completion(false, "HTTP Error \(httpResponse.statusCode)")
}
}
}.resume()
}
// Usage
if let audioURL = Bundle.main.url(forResource: "song", withExtension: "mp3") {
extractSnippet(audioURL: audioURL, apiKey: "hsa_your_api_key_here") { success, message in
DispatchQueue.main.async {
if success {
print("🎵 Success! \(message ?? "")")
} else {
print("💔 Failed: \(message ?? "Unknown error")")
}
}
}
}
// Java with OkHttp - Enhanced Error Handling
import okhttp3.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.concurrent.TimeUnit;
import org.json.JSONObject;
import org.json.JSONException;
public void extractSnippet(File audioFile, String apiKey) {
// Check if file exists
if (!audioFile.exists()) {
Log.e("API", "❌ Error: File not found: " + audioFile.getPath());
return;
}
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.build();
RequestBody fileBody = RequestBody.create(
MediaType.parse("audio/mpeg"),
audioFile
);
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", audioFile.getName(), fileBody)
.build();
Request request = new Request.Builder()
.url("https://www.harmonysnippetsai.com/api/v1/extract-snippet")
.addHeader("X-API-Key", apiKey)
.post(requestBody)
.build();
Log.d("API", "🔄 Uploading " + audioFile.getName() + "...");
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d("API", "📡 Response status: " + response.code());
if (response.isSuccessful()) {
String responseBody = response.body().string();
try {
JSONObject json = new JSONObject(responseBody);
if (json.getBoolean("success")) {
String base64Audio = json.getJSONObject("data").getString("snippet_base64");
byte[] audioData = Base64.getDecoder().decode(base64Audio);
// Save to internal storage
File outputFile = new File(context.getFilesDir(), "snippet.wav");
FileOutputStream fos = new FileOutputStream(outputFile);
fos.write(audioData);
fos.close();
Log.d("API", "✅ Snippet saved to " + outputFile.getPath());
} else {
String error = json.optString("error", "Unknown error");
Log.e("API", "❌ API Error: " + error);
}
} catch (JSONException e) {
Log.e("API", "❌ Error: Server returned non-JSON response");
Log.e("API", "📄 Response content: " + responseBody.substring(0, Math.min(500, responseBody.length())) + "...");
}
} else {
String responseBody = response.body().string();
try {
JSONObject json = new JSONObject(responseBody);
String error = json.optString("error", "HTTP Error " + response.code());
Log.e("API", "❌ Error: " + error);
} catch (JSONException e) {
Log.e("API", "❌ HTTP Error " + response.code());
Log.e("API", "📄 Response content: " + responseBody.substring(0, Math.min(500, responseBody.length())) + "...");
}
}
}
@Override
public void onFailure(Call call, IOException e) {
if (e.getMessage().contains("timeout")) {
Log.e("API", "❌ Error: Request timed out");
} else {
Log.e("API", "❌ Connection error: " + e.getMessage());
}
}
});
}
{
"success": true,
"data": {
"snippet_base64": "UklGRiQAAABXQVZFZm10...",
"original_duration": 180.5,
"snippet_duration": 10,
"format": "wav",
"sample_rate": 22050
},
"usage": {
"calls_used": 15,
"daily_limit": 60,
"remaining": 45
}
}
{
"error": "File too large. Maximum size: 10MB",
"limit": 60,
"used": 59
}
Sometimes the server may return plain text or HTML error messages. Your code should handle both JSON and non-JSON responses gracefully.
Internal Server Error
or
<html><head><title>Error</title></head><body>Service unavailable</body></html>
| Plan | Daily API Calls | Max File Size | Max Duration |
|---|---|---|---|
| Free | 60 calls | 10MB | 2.5 minutes |
| Pro | 1000 calls | 40MB | 4 minutes |
Check your API usage:
curl -H "X-API-Key: your_api_key_here" \
https://www.harmonysnippetsai.com/api/usage
Example response:
{
"success": true,
"data": {
"today_usage": 15,
"month_usage": 450,
"daily_limit": 60,
"remaining_today": 45,
"plan_type": "free"
}
}
400 - Bad Request (invalid file, missing parameters)401 - Unauthorized (invalid or missing API key)413 - File too large429 - Rate limit exceeded500 - Server errorNeed help? Email us at [email protected] with your API key and error details.