It looks like you're aiming to iterate through a list of messages, convert each message to speech using edge_tts, save the audio files, and play them sequentially. There are a few issues in your current script that need addressing:
- Missing Loop: There's no loop to iterate over the
messages list.
- Undefined Variable
i: The variable i is used but not defined.
- Incorrect Triple Quotes: Some messages have quadruple quotes (
""""), which causes syntax errors.
- Mixing
asyncio with time.sleep: Using time.sleep in an asynchronous function can block the event loop. Instead, use await asyncio.sleep().
- Blocking
playsound: The playsound function is blocking and might interfere with the asynchronous flow.
Below is a corrected and improved version of your script addressing these issues:
import asyncio
import edge_tts
from playsound import playsound
import os
from typing import List
# Corrected list of messages with proper triple quotes
messages: List[str] = [
"""Success is not final, failure is not fatal: It is the courage to continue that counts. – Winston Churchill""",
"""The only limit to our realization of tomorrow is our doubts of today. – Franklin D. Roosevelt""",
"""Don't watch the clock; do what it does. Keep going. – Sam Levenson""",
"""Believe you can, and you're halfway there. – Theodore Roosevelt""",
"""Start where you are. Use what you have. Do what you can. – Arthur Ashe""",
"""It does not matter how slowly you go, as long as you do not stop. – Confucius""",
"""Hardships often prepare ordinary people for an extraordinary destiny. – C.S. Lewis""",
"""Your present circumstances don't determine where you can go; they merely determine where you start. – Nido Qubein""",
"""You are never too old to set another goal or to dream a new dream. – C.S. Lewis""",
"""Success usually comes to those who are too busy to be looking for it. – Henry David Thoreau""",
"""The only way to achieve the impossible is to believe it is possible. – Charles Kingsleigh""",
"""Don't limit your challenges. Challenge your limits.""",
"""It always seems impossible until it's done.""",
"""What lies behind us and what lies before us are tiny matters compared to what lies within us. – Ralph Waldo Emerson""",
"""If you want to lift yourself up, lift up someone else. – Booker T. Washington""",
"""Perseverance is not a long race; it is many short races one after the other. – Walter Elliot""",
"""Great things never came from comfort zones.""",
"""Failure will never overtake me if my determination to succeed is strong enough. – Og Mandino""",
"""Act as if what you do makes a difference. It does. – William James""",
"""Success is the sum of small efforts, repeated day in and day out. – Robert Collier""",
]
async def synthesize_speech(text: str, voice: str, output_file: str):
"""Synthesize speech using edge_tts and save to a file."""
communicate = edge_tts.Communicate(text=text, voice=voice)
await communicate.save(output_file)
def play_audio(file_path: str):
"""Play the audio file using playsound."""
try:
playsound(file_path)
except Exception as e:
print(f"Error playing {file_path}: {e}")
async def main():
voice = "bn-IN-BashkarNeural" # Specify your desired voice
for idx, message in enumerate(messages, start=1):
output_file = os.path.abspath(f"audio_{idx}.mp3")
print(f"Synthesizing message {idx}/{len(messages)}...")
# Synthesize and save the audio
await synthesize_speech(message, voice, output_file)
# Check if the file was created successfully
if os.path.exists(output_file):
print(f"Playing {output_file}...")
# Play the audio
# Since playsound is blocking, run it in a separate thread to prevent blocking the event loop
loop = asyncio.get_event_loop()
await loop.run_in_executor(None, play_audio, output_file)
else:
print(f"Failed to create {output_file}.")
# Optional: Add a short delay between messages
await asyncio.sleep(0.5)
if __name__ == "__main__":
asyncio.run(main())
Key Improvements and Explanations:
-
Looping Through Messages:
- A
for loop iterates over each message, providing both the index (idx) and the message content.
-
Fixed Triple Quotes:
- Adjusted the
messages list to use proper triple quotes (""") ensuring valid syntax.
-
Separated Concerns with Functions:
synthesize_speech Function: Handles the text-to-speech synthesis using edge_tts and saves the output.
play_audio Function: Manages playing the audio file and handles any exceptions during playback.
-
Asynchronous Execution:
synthesize_speech is an async function and is awaited within the loop.
- Playing Audio Asynchronously:
playsound is inherently blocking. To prevent it from blocking the entire event loop, it's run in a separate thread using loop.run_in_executor.
- This allows
playsound to execute without halting other asynchronous tasks.
-
Using asyncio.sleep Instead of time.sleep:
- Replaced
time.sleep(0.5) with await asyncio.sleep(0.5) to ensure the event loop remains responsive.
-
Voice Configuration:
- The voice is specified once at the beginning (
voice = "bn-IN-BashkarNeural") and reused for all messages. Adjust this as needed for different voices.
-
File Naming:
- Audio files are named sequentially (
audio_1.mp3, audio_2.mp3, etc.) to avoid overwriting and to keep track of the order.
-
Error Handling:
- Checks if the audio file was successfully created before attempting to play it.
- Catches and prints any exceptions that occur during audio playback.
Additional Recommendations:
Dependencies Installation
Ensure you have the necessary libraries installed. You can install them using pip:
pip install edge-tts playsound
Note: The playsound library has different dependencies depending on the operating system:
- Windows: No additional dependencies.
- macOS: Uses the
afplay command.
- Linux: You might need to install
ffplay or mpg123 using your package manager.
For example, on Ubuntu:
sudo apt-get install ffmpeg
Final Thoughts
This revised script should achieve your goal of synthesizing and playing each message sequentially. Ensure that the edge_tts voice (bn-IN-BashkarNeural in this case) is correctly specified and available. You can explore different voices supported by edge_tts to suit your needs.