Exporting Text to Speech as an MP3 Audio File Using Python 3 and Microsoft Edge TTS Engine
Text-to-speech (TTS) technology is a powerful way to convert written text into spoken words, and Python makes it easy to work with TTS engines. In this guide, we’ll show you how to use Python 3 with the Microsoft Edge TTS engine to export text as an MP3 audio file.
Prerequisites
Before we dive into the steps, ensure you have the following:
- Python 3 Installed: Download and install Python 3 from python.org.
- Microsoft Edge Installed: The Edge browser comes pre-installed on most modern Windows systems.
- Edge TTS Library: Install the
edge-tts
package to interact with the Microsoft Edge TTS engine.
Step 1: Install Required Python Libraries
Open a terminal or command prompt and run the following command to install the edge-tts
library:
1 |
pip install edge-tts |
This library enables you to utilize Microsoft Edge’s TTS capabilities from Python.
Step 2: Write the Python Script
Create a Python script file, e.g., export_tts.py
, and add the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import asyncio from edge_tts import Communicate async def text_to_speech(text, output_file): """ Convert text to speech and save it as an MP3 file. Args: text (str): The text to convert to speech. output_file (str): The path to save the MP3 file. """ communicate = Communicate(text, voice="en-US-GuyNeural") # Change the voice as needed await communicate.save(output_file) if __name__ == "__main__": # Input text to convert to speech input_text = "Hello! This is a sample text-to-speech conversion using Microsoft Edge." # Output MP3 file path output_mp3 = "output.mp3" # Run the TTS conversion asyncio.run(text_to_speech(input_text, output_mp3)) print(f"Audio file saved as {output_mp3}") |
- Change the Text: Replace the
input_text
variable with your desired text. - Choose a Voice: The
voice
parameter in theCommunicate
function specifies the TTS voice. You can find available voices in the Microsoft Edge TTS documentation. - Set the Output File Path: Modify
output_mp3
to define where the MP3 file will be saved.
Step 4: Run the Script
Execute the script in your terminal or command prompt:
1 |
python export_tts.py |
Step 5: Verify the MP3 File
Locate the output.mp3
file in your specified directory and play it using any media player to ensure the TTS conversion worked as expected.