大家好,我是Python進階者。
一、前言
前幾天在Python白銀交流群【Python 小白】問了一個Python庫運作的問題,提問截圖如下:
下面是他的代碼:
import pyttsx3 #import the library
def voiceChange():
eng = pyttsx3.init() #initialize an instance
voice = eng.getProperty('voices') #get the available voices
# eng.setProperty('voice', voice[0].id) #set the voice to index 0 for male voice
eng.setProperty('voice', voice[1].id) #changing voice to index 1 for female voice
eng.say("This is a demonstration of how to convert index of voice using pyttsx3 library in python.") #say method for passing text to be spoken
eng.runAndWait() #run and process the voice command
if __name__ == "__main__":
voiceChange()
看上去這個代碼是網上擷取的。
二、實作過程
這裡【dcpeng】嘗試改了下,但是不太行。
還是女聲!這裡在網上查了下資料,還是需要修改系統資料庫才行,這裡也需要感謝【hugo】大佬的指導。本身Windows 10自帶了5種聲音,如下所示:
其中Kangkang就是男聲音,但是在系統資料庫裡邊,這個Kangkang是沒有加載進去的,預設就隻加載了Huihui和Zira兩個女聲。
上圖中的Kangkang是後來我自己加上去,原本是沒有的,具體的加載教程看這裡了。修改系統資料庫的方法:可以私信。
之後再運作代碼的話,就可以看到Kangkang也加載到控制台了,現在也可以發出男聲了。
具體代碼如下:
import pyttsx3 # 導入庫
def textToVoice():
# eng = pyttsx3.init() # 初始化一個執行個體
eng = pyttsx3.init()
voice = eng.getProperty('voices')
# print(voice)
# for i in voice:
# print(i)
eng.setProperty('voice', voice[2].id)
eng.say("感謝大佬!太強了 太強了 太強了")
# say 用于傳遞要說的文本的方法
eng.runAndWait() # 運作并處理語音指令
if __name__ == "__main__":
textToVoice()
經過測試确實好使!
三、總結
大家好,我是皮皮。這篇文章主要盤點了一個Python庫處理的問題,文中針對該問題,給出了具體的解析和代碼實作,幫助粉絲順利解決了問題。