Skip to content

Instantly share code, notes, and snippets.

@simlated
Last active February 29, 2024 20:48
Show Gist options
  • Save simlated/40bee9e4f0b0de5c097d395b3767504d to your computer and use it in GitHub Desktop.
Save simlated/40bee9e4f0b0de5c097d395b3767504d to your computer and use it in GitHub Desktop.
Get duration of an mp3 generated by Elevelabs API
import requests
from mutagen.mp3 import MP3
from io import BytesIO
# Your API key (replace <mykey> with your actual API key)
api_key = <mykey>
# Replace <voiceid> with your actual voice id value
voice_id=123456
url = f"https://api.elevenlabs.io/v1/text-to-speech/f{voice_id}"
# Request headers
headers = {
'Content-Type': 'application/json',
'xi-api-key': api_key,
}
# Request body
data = {
"text": "Hello! My name is Peter!",
"model_id": "eleven_multilingual_v2",
"voice_settings": {
"stability": 0.76,
"similarity_boost": 0.9
}
}
# Make the API request
response = requests.post(url, json=data, headers=headers)
# Check if the request was successful
if response.status_code == 200:
mp3_data = response.content
mp3_file_like = BytesIO(mp3_data)
# Load the MP3 file from the in-memory bytes
audio = MP3(mp3_file_like)
# Get the length/duration of the MP3 file in seconds
duration = audio.info.length
print(f"Duration: {duration} seconds")
else:
print(f"Error: {response.status_code}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment