edge-tts

repository·master·Indexed 11 days ago

https://github.com/rany2/edge-tts

A Python-based tool and module that interfaces with Microsoft Edge's online text-to-speech service. It provides a command-line interface and a programmable API via the Communicate class for streaming audio, saving MP3 files, and generating synchronized SRT subtitles using SubMaker.

Tokens
7K
Snippets
30
Records
32
Agent score
93%

What's inside edge-tts

  1. Install edge-tts

    master

    You can install edge-tts using pip to use it as a Python module, or using pipx if you only intend to use the edge-tts and edge-playback command-line tools.

    # Install as a Python module
    $ pip install edge-tts
    
    # Install only the CLI tools
    $ pipx install edge-tts
  2. List and change voices

    master

    To see all available voices, their gender, and personality traits, use the --list-voices option. To use a specific voice, provide its name via the --voice option.

    # List all available voices
    $ edge-tts --list-voices
    
    # Use a specific voice
    $ edge-tts --voice ar-EG-SalmaNeural --text "مرحبا كيف حالك؟" --write-media hello_in_arabic.mp3 --write-subtitles hello_in_arabic.srt
    $ edge-tts --list-voices
    $ edge-tts --voice ar-EG-SalmaNeural --text "مرحبا كيف حالك؟" --write-media hello_in_arabic.mp3 --write-subtitles hello_in_arabic.srt
  3. Play speech immediately with edge-playback

    master

    The edge-playback command allows you to play text-to-speech immediately with subtitles.

    Note: On non-Windows platforms, this command requires the mpv command-line player to be installed.

    edge-playback supports most edge-tts options except for --write-media, --write-subtitles, and --list-voices.

    $ edge-playback --text "Hello, world!"
  4. Use the edge-tts CLI to generate speech and subtitles

    master

    The edge-tts command allows you to convert text to speech and optionally save the output as an MP3 media file and an SRT subtitle file.

    $ edge-tts --text "Hello, world!" --write-media hello.mp3 --write-subtitles hello.srt
  5. Adjust speech rate, volume, and pitch

    master

    You can modify the speech characteristics using --rate, --volume, and --pitch.

    Important: When using negative values, you must use the --[option]=value syntax (e.g., --rate=-50%) instead of --rate -50% to prevent the shell from interpreting the negative value as a separate command-line option.

    # Adjust rate
    $ edge-tts --rate=-50% --text "Hello, world!" --write-media hello_with_rate_lowered.mp3 --write-subtitles hello_with_rate_lowered.srt
    
    # Adjust volume
    $ edge-tts --volume=-50% --text "Hello, world!" --write-media hello_with_volume_lowered.mp3 --write-subtitles hello_with_volume_lowered.srt
    
    # Adjust pitch
    $ edge-tts --pitch=-50Hz --text "Hello, world!" --write-media hello_with_pitch_lowered.mp3 --write-subtitles hello_with_pitch_lowered.srt
  6. Use SubMaker to generate SRT subtitles

    master

    The SubMaker class is used to generate subtitle files (specifically in SRT format) by processing WordBoundary or SentenceBoundary messages received from a TTS stream.

    To use it:

    1. Instantiate SubMaker.
    2. Call .feed(msg) for each TTSChunk message. The message must contain type, offset, duration, and text keys.
    3. Call .get_srt() to retrieve the final subtitle string.

    Note: The SubMaker expects consistent message types. Once you start feeding it WordBoundary messages, you cannot feed it SentenceBoundary messages (and vice versa) without raising a ValueError.

    from edge_tts.submaker import SubMaker
    
    submaker = SubMaker()
    
    # Example of feeding a WordBoundary message
    # offset and duration are typically in 100-microsecond units based on implementation
    submaker.feed({
        "type": "WordBoundary",
        "offset": 1000,
        "duration": 500,
        "text": "Hello"
    })
    
    # Retrieve the SRT content
    srt_content = submaker.get_srt()
    print(srt_content)
  7. Filter voices using VoicesManager

    master

    The VoicesManager class provides a way to search through available voices using specific attributes.

    1. Initialize: You must first call the class method VoicesManager.create() to populate the manager with voices. You can either let it fetch all available voices automatically or pass a custom list of Voice objects.
    2. Search: Use the .find(**kwargs) method to filter voices. The kwargs should match the keys available in the voice attribute dictionary (e.g., Gender, Locale, Language).

    Note: Calling .find() before .create() will raise a RuntimeError.

    from edge_tts import VoicesManager
    
    # Initialize the manager
    manager = await VoicesManager.create()
    
    # Find voices with specific attributes
    # Example: finding English female voices
    matching_voices = manager.find(Language="en", Gender="Female")
    
    for voice in matching_voices:
        print(voice)
  8. Use synchronous interfaces with save_sync() and stream_sync()

    master

    If you are working in a synchronous environment and cannot use asyncio.run(), Communicate provides synchronous wrappers that handle the event loop internally.

    • save_sync(audio_fname, metadata_fname): Synchronously saves audio and metadata to files.
    • stream_sync(): A synchronous generator that yields TTSChunk objects.
    # Synchronous saving
    communicate.save_sync("output.mp3")
    
    # Synchronous streaming
    for message in communicate.stream_sync():
        if message["type"] == "audio":
            print(f"Received {len(message['data'])} bytes of audio")
  9. Convert a single Subtitle to an SRT block with to_srt()

    master

    The to_srt() method on a Subtitle instance converts that specific subtitle into its individual SRT formatted block string.

    Parameters:

    • eol (str): The end of line string to use (default "\n").
    from datetime import timedelta
    from edge_tts.srt_composer import Subtitle
    
    sub = Subtitle(1, timedelta(seconds=1), timedelta(seconds=2), "Test")
    print(sub.to_srt())
  10. Reorder and reindex subtitles with sort_and_reindex()

    master

    If you need to manipulate the subtitle list (e.g., after changing timestamps) without immediately generating a string, use sort_and_reindex(). This function sorts subtitles by start time and updates their index attribute.

    Parameters:

    • subtitles: An iterable of Subtitle objects.
    • start_index (int): The index to start from (default 1).
    • in_place (bool): Whether to modify the objects in the original list.
    • skip (bool): If True (default), it filters out "useless" subtitles. A subtitle is skipped if:
      • Content is empty or only whitespace.
      • Start time is negative.
      • Start time is greater than or equal to the end time.
    from datetime import timedelta
    from edge_tts.srt_composer import Subtitle, sort_and_reindex
    
    subs = [
        Subtitle(index=1, start=timedelta(seconds=10), end=timedelta(seconds=12), content="Late"),
        Subtitle(index=2, start=timedelta(seconds=1), end=timedelta(seconds=2), content="Early"),
    ]
    
    # Returns a generator of sorted, reindexed subtitles
    sorted_subs = list(sort_and_reindex(subs))
    for s in sorted_subs:
        print(f"Index: {s.index}, Start: {s.start}")
  11. List all available voices with list_voices()

    master

    Use the list_voices() asynchronous function to retrieve a list of all available voices and their associated attributes. This function fetches data from the same endpoint used by Microsoft Edge. You can optionally provide a connector or a proxy string for the request.

    from edge_tts import list_voices
    
    voices = await list_voices(proxy="http://your-proxy:port")
    for voice in voices:
        print(voice)