async def get_voices() -> Dict[str, str]:
"""
Retrieve all available voices from the edge_tts service.
code
Returns:
A dictionary mapping voice descriptions to their short names.
"""
try:
voices = await edge_tts.list_voices()
return {
f"{v['ShortName']} - {v['Locale']} ({v['Gender']})": v['ShortName']
for v in voices
}
except Exception as e:
raise RuntimeError(f"Failed to retrieve voices: {e}")
async def text_to_speech(
text: str,
voice: str,
rate: int,
pitch: int,
output_path: Optional[str] = None
) -> str:
"""
Convert text to speech and save as an MP3 file.
code
Args:
text: The text to convert.
voice: The selected voice short name.
rate: Speech rate adjustment in percentage.
pitch: Pitch adjustment in Hz.
output_path: Optional path to save the output MP3 file.
Returns:
The file path to the generated MP3 audio.
Raises:
ValueError: If text or voice parameters are invalid.
RuntimeError: If TTS conversion fails.
"""
if not text.strip():
raise ValueError("Input text cannot be empty.")
if not voice.strip():
raise ValueError("A valid voice must be selected.")
rate_str = f"{rate:+d}%"
pitch_str = f"{pitch:+d}Hz"
communicator = edge_tts.Communicate(
text=text,
voice=voice,
rate=rate_str,
pitch=pitch_str
)
try:
if output_path:
await communicator.save(output_path)
return output_path
else:
with tempfile.NamedTemporaryFile(
delete=False, suffix=".mp3"
) as tmp_file:
tmp_path = tmp_file.name
await communicator.save(tmp_path)
return tmp_path
except Exception as e:
raise RuntimeError(f"Text-to-speech conversion failed: {e}")
Assistant
def parse_arguments(voices: Dict[str, str]) -> argparse.Namespace:
"""
Parse command-line arguments provided by the user.
code
Args:
voices: A dictionary of available voices.
Returns:
The populated namespace with parsed arguments.
"""
parser = argparse.ArgumentParser(
description="Voicecloning.be Text-to-Speech Command-Line Interface"
)
parser.add_argument(
"-t",
"--text",
type=str,
required=True,
help="Text to convert to speech."
)
parser.add_argument(
"-v",
"--voice",
type=str,
required=True,
choices=voices.keys(),
help="Voice to use for speech."
)
parser.add_argument(
"-r",
"--rate",
type=int,
default=0,
help="Speech rate adjustment in percentage (e.g., -10 for slower, +10 for faster). Default is 0."
)
parser.add_argument(
"-p",
"--pitch",
type=int,
default=0,
help="Pitch adjustment in Hz (e.g., -5 for lower, +5 for higher). Default is 0."
)
parser.add_argument(
"-o",
"--output",
type=str,
default=None,
help="Output file path for the generated MP3. If not provided, a temporary file will be used."
)
return parser.parse_args()
async def main() -> None:
"""
The main function to execute the CLI for text-to-speech conversion.
"""
try:
voices = await get_voices()
except RuntimeError as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
code
if not voices:
print("No voices available.", file=sys.stderr)
sys.exit(1)
args = parse_arguments(voices)
voice_short_name = voices.get(args.voice)
if not voice_short_name:
print("Selected voice is not available.", file=sys.stderr)
sys.exit(1)
try:
output_file = await text_to_speech(
text=args.text,
voice=voice_short_name,
rate=args.rate,
pitch=args.pitch,
output_path=args.output
)
print(f"Audio successfully saved to: {output_file}")
# Automatically play the audio
try:
print("Playing the audio...")
playsound(output_file)
except Exception as play_error:
print(f"Failed to play audio: {play_error}", file=sys.stderr)
except ValueError as ve:
print(f"Input Error: {ve}", file=sys.stderr)
sys.exit(1)
except RuntimeError as re:
print(f"Processing Error: {re}", file=sys.stderr)
sys.exit(1)
except Exception as ex:
print(f"An unexpected error occurred: {ex}", file=sys.stderr)
sys.exit(1)
if name == "main":
try:
asyncio.run(main())
except KeyboardInterrupt:
print("\nOperation cancelled by user.", file=sys.stderr)
sys.exit(1)
Certainly! Below is a Python script that implements a command-line interface (CLI) for text-to-speech (TTS) functionality without using the argparse and asyncio libraries. Instead, it leverages the sys module for argument parsing and the synchronous pyttsx3 library for TTS operations. The script also uses the playsound library to play the generated audio file.
Features
Command-Line Arguments: Parses command-line arguments manually using sys.argv.
Text-to-Speech Conversion: Utilizes pyttsx3 to convert text to speech.
Voice Selection: Lists available voices and allows the user to select one.
Speech Rate Adjustment: Adjusts the speech rate based on user input.
Save Audio File: Saves the generated speech to an MP3 file.
Play Audio: Automatically plays the saved audio file using playsound.
Prerequisites
Before running the script, ensure you have the necessary libraries installed:
bash
pip install pyttsx3 playsound
Note: On some platforms, additional dependencies might be required for pyttsx3 to function correctly. Please refer to the pyttsx3 documentation for platform-specific setup.
Script: tts_cli.py
python
import sys
import pyttsx3
import tempfile
from playsound import playsound
import os
def print_usage():
usage = """
Usage: python tts_cli.py -t "Your text here" [options]
Options:
-t, --text Text to convert to speech. (Required)
-v, --voice Voice ID to use for speech. (Optional)
-r, --rate Speech rate adjustment (integer). Positive for faster, negative for slower. Default is 0.
-o, --output Output file path for the generated audio. If not provided, a temporary file will be used.
-h, --help Show this help message and exit.
Example:
python tts_cli.py -t "Hello, world!" -v "com.apple.speech.synthesis.voice.Alex" -r 20 -o output.mp3
"""
print(usage)
def parse_arguments(args):
parsed_args = {
'text': None,
'voice': None,
'rate': 0,
'output': None
}
if not args or '-h' in args or '--help' in args:
print_usage()
sys.exit(0)
i = 0
while i < len(args):
arg = args[i]
if arg in ('-t', '--text'):
if i + 1 < len(args):
parsed_args['text'] = args[i + 1]
i += 2
else:
print("Error: Missing value for text.")
print_usage()
sys.exit(1)
elif arg in ('-v', '--voice'):
if i + 1 < len(args):
parsed_args['voice'] = args[i + 1]
i += 2
else:
print("Error: Missing value for voice.")
print_usage()
sys.exit(1)
elif arg in ('-r', '--rate'):
if i + 1 < len(args):
try:
parsed_args['rate'] = int(args[i + 1])
except ValueError:
print("Error: Rate must be an integer.")
print_usage()
sys.exit(1)
i += 2
else:
print("Error: Missing value for rate.")
print_usage()
sys.exit(1)
elif arg in ('-o', '--output'):
if i + 1 < len(args):
parsed_args['output'] = args[i + 1]
i += 2
else:
print("Error: Missing value for output.")
print_usage()
sys.exit(1)
else:
print(f"Unknown argument: {arg}")
print_usage()
sys.exit(1)
return parsed_args
def list_voices(engine):
voices = engine.getProperty('voices')
print("Available Voices:")
for idx, voice in enumerate(voices):
print(f"{idx + 1}. ID: {voice.id}, Name: {voice.name}, Lang: {voice.languages}, Gender: {voice.gender}")
print()
def select_voice(engine, voice_id=None):
voices = engine.getProperty('voices')
if voice_id:
for voice in voices:
if voice.id == voice_id:
return voice.id
print(f"Warning: Voice ID '{voice_id}' not found. Using default voice.")
return engine.getProperty('voice') # Return default voice ID
def main():
# Parse command-line arguments
args = parse_arguments(sys.argv[1:])
if not args['text']:
print("Error: Text is required.")
print_usage()
sys.exit(1)
# Initialize pyttsx3 engine
engine = pyttsx3.init()
# List available voices if no voice is specified
if not args['voice']:
print("No voice specified. Listing available voices:")
list_voices(engine)
# Select voice
selected_voice = select_voice(engine, args['voice'])
engine.setProperty('voice', selected_voice)
# Adjust speech rate
default_rate = engine.getProperty('rate') # Default rate
new_rate = default_rate + args['rate']
engine.setProperty('rate', new_rate)
# Determine output file path
if args['output']:
output_path = args['output']
else:
# Create a temporary file
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
output_path = temp_file.name
temp_file.close()
try:
# Save speech to file
engine.save_to_file(args['text'], output_path)
engine.runAndWait()
print(f"Audio successfully saved to: {output_path}")
# Play the audio file
print("Playing the audio...")
playsound(output_path)
except Exception as e:
print(f"Error during TTS processing: {e}")
sys.exit(1)
finally:
# Clean up temporary file if no output path was specified
if not args['output']:
try:
os.remove(output_path)
except Exception:
pass
if __name__ == "__main__":
main()
How It Works
Argument Parsing: The script manually parses command-line arguments using the sys.argv list. It supports the following flags:
-t or --text: (Required) The text you want to convert to speech.
-v or --voice: (Optional) The ID of the voice to use. If not specified, the script lists available voices.
-r or --rate: (Optional) Adjusts the speech rate. Positive values make the speech faster, while negative values make it slower. Default is 0 (no change).
-o or --output: (Optional) The file path where the audio will be saved. If not provided, a temporary file is used.
-h or --help: Displays the usage information.
Listing Voices: If no voice is specified, the script lists all available voices on your system, allowing you to choose one by specifying its ID.
Voice Selection: The script sets the selected voice. If an invalid voice ID is provided, it defaults to the system's default voice and issues a warning.
Adjusting Speech Rate: The speech rate is adjusted based on the user's input. You can make the speech faster by providing a positive integer or slower with a negative integer.
Saving Audio: The pyttsx3 engine saves the converted speech to an MP3 file. If no output path is provided, a temporary file is created and used.
Playing Audio: After saving, the script automatically plays the audio file using the playsound library.
Cleanup: If a temporary file was used (i.e., no output path was specified), the script attempts to delete it after playback.
Examples
Basic Usage: Convert text to speech with default settings.
python tts_cli.py -t "This audio will be saved to a file." -o my_audio.mp3
Display Help:
bash
python tts_cli.py -h
Notes
Voice IDs: Voice IDs vary based on the operating system and installed voices. Use the -v flag followed by a valid voice ID to specify a voice. Run the script without the -v flag to list available voices.
Speech Rate: Adjusting the speech rate too much might result in unnatural-sounding speech. It's advisable to use small integers for subtle changes.
Error Handling: The script includes basic error handling for missing arguments and invalid inputs. Ensure that the paths provided for the output file are valid and writable.
Temporary Files: If an output path isn't specified, the script creates a temporary MP3 file for playback, which is deleted after playback. Ensure that the environment permits file creation and deletion in temporary directories.
Conclusion
This script provides a straightforward way to convert text to speech from the command line without relying on argparse and asyncio. By using sys.argv for argument parsing and pyttsx3 for TTS operations, the script remains simple and easy to understand, while still offering flexibility in voice selection, speech rate adjustment, and audio file management.
Feel free to customize and extend the script further to suit your specific needs!