Table of Contents
Python text to speech (research & finished product function)
What is speech synthesis technology?
How to implement it with code?
gTTS library
pyttsx3 library
speech Library
Home Backend Development Python Tutorial How to use the Python third-party library gTTs/pyttsx3/speech

How to use the Python third-party library gTTs/pyttsx3/speech

May 12, 2023 pm 06:43 PM
python speech

Python text to speech (research & finished product function)

Due to project needs, I need toconvert text to speech, so the first step is to conduct research

What is speech synthesis technology?

Speech synthesis (text to speech), referred to as TTS. It is a technology that converts text into speech. It allows the computer to simulate the human mouth and express what it wants to express through different timbres. It is part of the human-computer dialogue.
TTS can intelligently convert text into natural speech flow through the design of neural network. The greatly facilitates the use of visually impaired patients and also improves the readability of the text. TTS applications include speech-driven hardware and sound-sensitive systems, and are often used with voice recognition programs.

Now many manufacturers have launched their own speech synthesis services or APIs, and you can also check them out by yourself. This article only conducts research on third-party speech synthesis libraries in the Python environment

How to implement it with code?

As mentioned above, although there are many products on the market,As a developer, I want a free tool that can debug code , After searching for materials, I found that the gTTs library, pyttsx3 library, and speech library can meet my needs. Let's make a horizontal comparison, which can save everyone from taking detours.

Third-party library name Requires internet connection Supports Chinese and English Supports Japanese Adjustable speaking speed Like human voice level
ggts X is very similar to navigation
pyttsx3 X X Suitable for reading novels
speech X X X Much like faster navigation

gTTS library

gTTS Library (Google Text-to-Speech): Used to interact with Google Translate's text-to-speech API. Write voice mp3 data to a file
Advantages: Supports multiple languages ​​including Chinese, English and Japanese, supported by Google Translate API, the human voice is quite nice
Disadvantages: Does not support speech speed adjustment, must be used every time Scientific Internet access cannot be used on a stand-alone computer

In the voice playback function, we have chosen two methods

  • The first is to automatically play the audio in the playsound library (the playback progress cannot be adjusted)

  • The second is that the os library calls the system’s own player (adjustable progress)

Please seeplaysound library play& GTTS library to textfunction

# 函数功能: 用gtts库阅读文本,保存为.mp3文件后, 用系统内置的浏览器阅读出来, 打开mp3文件, 函数执行结束(播放方式为os库)
def gtts_os_debug(text,mp3_filepath,language):#参数说明:参数1是朗读的文字,参数2是保存路径,参数3是数字{0英文,1中文,2日语}
    #大成功,可惜的是os调用自带播放器, 实际上只执行了"打开mp3"的操作, 它并不会在音频播报完后再进行下一条语句
    from gtts import gTTS
    import os
    # 已知zh-tw版本违和感较高,所以我们用zh-CN来进行后续工作
    if int(language) ==0 :
        s = gTTS(text=text, lang='en', tld='com')
        # s = gTTS(text=text, lang='en', tld='co.uk')#我比较喜欢美音,但是如果你喜欢英国口音可以尝试这个
    elif int(language) ==1 :
        s = gTTS(text=text, lang='zh-CN')
    elif int(language) ==2 :
        s = gTTS(text=text, lang='ja')
    try:
        s.save(mp3_filepath)
    except:
        os.remove(mp3_filepath)
        print(mp3_filepath,"文件已经存在,但是没有关系!已经删掉了")
        s.save(mp3_filepath)
    print(mp3_filepath,"保存成功")
    os.system(mp3_filepath)#调用系统自带的播放器播放MP3
gtts_os_debug(text="I'm gtts library,from google Artificial Intelligence & Google Translate.",mp3_filepath="gtts英文测试.mp3",language=0)
gtts_os_debug(text="我是gtts库, 你想听听我的声音吗",mp3_filepath="gtts中文测试.mp3",language=1)
gtts_os_debug(text="真実はいつもひとつ" ,mp3_filepath="gtts日语测试.mp3",language=2)
Copy after login

Please seeos library playback & GTTS library to textfunction

# 函数功能: 用gtts库阅读文本,保存为.mp3文件后, 用playsound库阅读出来, 阅读完毕, 函数执行结束
def gtts_debug(text,mp3_filepath,language):#参数说明:参数1是朗读的文字,参数2是保存路径,参数3是数字{0英文,1中文,2日语}
    #大成功,已经实现了定制化文字转语音,但是播放的playsound需要改进(playsound库本身可能会出现bug...)
    from gtts import gTTS
    from playsound import playsound
    import os
    if int(language) ==0 :
        s = gTTS(text=text, lang='en', tld='com')
        # s = gTTS(text=text, lang='en', tld='co.uk')#我比较喜欢美音,但是如果你喜欢英国口音可以尝试这个
    elif int(language) ==1 :
        s = gTTS(text=text, lang='zh-CN')
    elif int(language) ==2 :
        s = gTTS(text=text, lang='ja')
    try:
        s.save(mp3_filepath)
    except:
        os.remove(mp3_filepath)
        print(mp3_filepath,"文件已经存在,但是没有关系!已经删掉了")
        s.save(mp3_filepath)
    print(mp3_filepath,"保存成功")
    playsound(mp3_filepath)
gtts_debug(text="I'm gtts library,from google Artificial Intelligence & Google Translate.",mp3_filepath="gtts英文测试.mp3",language=0)
gtts_debug(text="我是gtts库, 你想听听我的声音吗",mp3_filepath="gtts中文测试.mp3",language=1)
gtts_debug(text="真実はいつもひとつ" ,mp3_filepath="gtts日语测试.mp3",language=2)
Copy after login

pyttsx3 library

pyttsx3 library: It is a text-to-speech conversion library in Python, it can work offline
Advantages: Can work offline, supports direct speech reading, adjustable volume and speed
Disadvantages: Initially only English (Female) and Chinese (Female) voice packs, voice packs in other languages ​​need to be downloaded separately

Please seepyttsx3 library to convert text & self-readingFunction

def pyttsx3_debug(text,language,rate,volume,filename,sayit=0):
    #参数说明: 六个重要参数,阅读的文字,语言(0-英文/1-中文),语速,音量(0-1),保存的文件名(以.mp3收尾),是否发言(0否1是)
    import pyttsx3
    engine = pyttsx3.init()  # 初始化语音引擎
    engine.setProperty('rate', rate)  # 设置语速
    #速度调试结果:50戏剧化的慢,200正常,350用心听小说,500敷衍了事
    engine.setProperty('volume', volume)  # 设置音量
    voices = engine.getProperty('voices')  # 获取当前语音的详细信息
    if int(language)==0:
        engine.setProperty('voice', voices[0].id)  # 设置第一个语音合成器 #改变索引,改变声音。0中文,1英文(只有这两个选择)
    elif int(language)==1:
        engine.setProperty('voice', voices[1].id)
    if int(sayit)==1:
        engine.say(text)  # pyttsx3->将结果念出来
    elif int(sayit)==0:
        print("那我就不念了哈")
    engine.save_to_file(text, filename) # 保存音频文件
    print(filename,"保存成功")
    engine.runAndWait() # pyttsx3结束语句(必须加)
    engine.stop() # pyttsx3结束语句(必须加)
pyttsx3_debug(text="我是pyttsx3, 初次见面, 给您拜个早年",language=0,rate=200,volume=0.9,filename="ptttsx3中文测试.mp3",sayit=1)
pyttsx3_debug(text="I'm fake Siri, your smart voice Manager",language=1,rate=200,volume=0.9,filename="ptttsx3英文测试.mp3",sayit=1)
Copy after login

speech Library

speech: Windows-based speech synthesis module, one line of code can realize reading
Advantages: Relying on Windows system, installation and use are extremely simple and super convenient.
Suitable for the code debugging process, let the cold AI language wake me up from writing bugs QAQ
Disadvantages: only system language (Chinese & English), does not support speech speed adjustment and audio export

Please seespeech to textfunction

import speech
speech.say("甘霖娘,又出bug了")
speech.say("Don't ask me .I have no idea why bug exist again")
# 如你所见, 代码编译究极简单, 而且单机, 但是!每次使用都会呼出微软语音助手...
Copy after login

The above is the detailed content of How to use the Python third-party library gTTs/pyttsx3/speech. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles