search
HomeBackend DevelopmentPython TutorialHow to use the Python third-party library gTTs/pyttsx3/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)

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)

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)

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")
# 如你所见, 代码编译究极简单, 而且单机, 但是!每次使用都会呼出微软语音助手...

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
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

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

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.