Introduction
Ever needed a quick sound effect for a project, but didn't have a sound designer or the time to find the right audio clip? What if you could generate it from a simple text prompt using a powerful AI?
In this quick tutorial, we'll walk through how to use the ElevenLabs API and Python to create a custom sound effect, like "a dramatic explosion," with just a few lines of code. This is perfect for indie game developers, content creators, or anyone looking to add a little flair to their projects.
Install
pip install elevenlabs==2.9.1
pip install python-dotenv==1.1.1
Create an account in Elevenlabs from here
Create an API key and
Make sure that Sound Effects is "Has Access"
The Code
Here is the simple Python script we'll be using.
import os
from dotenv import load_dotenv
from elevenlabs.client import ElevenLabs
load_dotenv()
elevenlabs = ElevenLabs(
api_key=os.getenv("ELEVENLABS_API_KEY"),
)
text_to_convert = "a dramatic explosion"
# The convert method returns a generator by default
audio_generator = elevenlabs.text_to_sound_effects.convert(
text=text_to_convert
)
# Join the audio chunks from the generator into a single bytes object
audio_bytes = b"".join(audio_generator)
# Now, write the single bytes object to the file
with open("explosion.mp3", "wb") as f:
f.write(audio_bytes)
print(f"Sound effect for '{text_to_convert}' saved to explosion.mp3")
How It Works
Dependencies: We start by importing the necessary libraries: os for handling environment variables, dotenv to load our API key, and elevenlabs for the core functionality.
Authentication: We initialize the ElevenLabs client with our API key, which is securely loaded from a .env file. This is a best practice for keeping your credentials safe.
The Magic: The text_to_sound_effects.convert() method is the heart of the script. It takes a text description—in this case, "a dramatic explosion"—and sends it to the ElevenLabs AI model.
Handling the Output: The method returns an audio generator, which we then join into a single bytes object. This is a crucial step to ensure the entire audio clip is saved correctly.
Saving the File: Finally, the code writes the bytes object to a file named explosion.mp3 and prints a confirmation message.
Conclusion & Call to Action
With just this small script, you can bring your ideas to life with custom audio. The ElevenLabs API offers a wide range of possibilities for creating unique sound effects and voiceovers.
Want to try it yourself? You can get started with the ElevenLabs text-to-sound effects tool for free.
Top comments (0)