Python實(shí)現(xiàn)語音識別和語音合成功能
聲音的本質(zhì)是震動,震動的本質(zhì)是位移關(guān)于時間的函數(shù),波形文件(.wav)中記錄了不同采樣時刻的位移。
通過傅里葉變換,可以將時間域的聲音函數(shù)分解為一系列不同頻率的正弦函數(shù)的疊加,通過頻率譜線的特殊分布,建立音頻內(nèi)容和文本的對應(yīng)關(guān)系,以此作為模型訓(xùn)練的基礎(chǔ)。
案例:畫出語音信號的波形和頻率分布,(freq.wav數(shù)據(jù)地址)
# -*- encoding:utf-8 -*-
import numpy as np
import numpy.fft as nf
import scipy.io.wavfile as wf
import matplotlib.pyplot as plt
sample_rate, sigs = wf.read('../machine_learning_date/freq.wav')
print(sample_rate) # 8000采樣率
print(sigs.shape) # (3251,)
sigs = sigs / (2 ** 15) # 歸一化
times = np.arange(len(sigs)) / sample_rate
freqs = nf.fftfreq(sigs.size, 1 / sample_rate)
ffts = nf.fft(sigs)
pows = np.abs(ffts)
plt.figure('Audio')
plt.subplot(121)
plt.title('Time Domain')
plt.xlabel('Time', fontsize=12)
plt.ylabel('Signal', fontsize=12)
plt.tick_params(labelsize=10)
plt.grid(linestyle=':')
plt.plot(times, sigs, c='dodgerblue', label='Signal')
plt.legend()
plt.subplot(122)
plt.title('Frequency Domain')
plt.xlabel('Frequency', fontsize=12)
plt.ylabel('Power', fontsize=12)
plt.tick_params(labelsize=10)
plt.grid(linestyle=':')
plt.plot(freqs[freqs >= 0], pows[freqs >= 0], c='orangered', label='Power')
plt.legend()
plt.tight_layout()
plt.show()

語音識別
梅爾頻率倒譜系數(shù)(MFCC)通過與聲音內(nèi)容密切相關(guān)的13個特殊頻率所對應(yīng)的能量分布,可以使用梅爾頻率倒譜系數(shù)矩陣作為語音識別的特征。基于隱馬爾科夫模型進(jìn)行模式識別,找到測試樣本最匹配的聲音模型,從而識別語音內(nèi)容。
MFCC
梅爾頻率倒譜系數(shù)相關(guān)API:
import scipy.io.wavfile as wf
import python_speech_features as sf
sample_rate, sigs = wf.read('../data/freq.wav')
mfcc = sf.mfcc(sigs, sample_rate)
案例:畫出MFCC矩陣:
python -m pip install python_speech_features import scipy.io.wavfile as wf import python_speech_features as sf import matplotlib.pyplot as mp sample_rate, sigs = wf.read( '../ml_data/speeches/training/banana/banana01.wav') mfcc = sf.mfcc(sigs, sample_rate) mp.matshow(mfcc.T, cmap='gist_rainbow') mp.show()

隱馬爾科夫模型
隱馬爾科夫模型相關(guān)API:
import hmmlearn.hmm as hl model = hl.GaussianHMM(n_components=4, covariance_type='diag', n_iter=1000) # n_components: 用幾個高斯分布函數(shù)擬合樣本數(shù)據(jù) # covariance_type: 相關(guān)矩陣的輔對角線進(jìn)行相關(guān)性比較 # n_iter: 最大迭代上限 model.fit(mfccs) # 使用模型匹配測試mfcc矩陣的分值 score = model.score(test_mfccs)
案例:訓(xùn)練training文件夾下的音頻,對testing文件夾下的音頻文件做分類
1、讀取training文件夾中的訓(xùn)練音頻樣本,每個音頻對應(yīng)一個mfcc矩陣,每個mfcc都有一個類別(apple)。
2、把所有類別為apple的mfcc合并在一起,形成訓(xùn)練集。
| mfcc | |
| mfcc | apple |
| mfcc | |
.....
由上述訓(xùn)練集樣本可以訓(xùn)練一個用于匹配apple的HMM。
3、訓(xùn)練7個HMM分別對應(yīng)每個水果類別。 保存在列表中。
4、讀取testing文件夾中的測試樣本,整理測試樣本
| mfcc | apple |
| mfcc | lime |
5、針對每一個測試樣本:
1、分別使用7個HMM模型,對測試樣本計(jì)算score得分。
2、取7個模型中得分最高的模型所屬類別作為預(yù)測類別。
import os
import numpy as np
import scipy.io.wavfile as wf
import python_speech_features as sf
import hmmlearn.hmm as hl
#1. 讀取training文件夾中的訓(xùn)練音頻樣本,每個音頻對應(yīng)一個mfcc矩陣,每個mfcc都有一個類別(apple)。
def search_file(directory):
# 使傳過來的directory匹配當(dāng)前操作系統(tǒng)
# {'apple':[url, url, url ... ], 'banana':[...]}
directory = os.path.normpath(directory)
objects = {}
# curdir:當(dāng)前目錄
# subdirs: 當(dāng)前目錄下的所有子目錄
# files: 當(dāng)前目錄下的所有文件名
for curdir, subdirs, files in os.walk(directory):
for file in files:
if file.endswith('.wav'):
label = curdir.split(os.path.sep)[-1]
if label not in objects:
objects[label] = []
# 把路徑添加到label對應(yīng)的列表中
path = os.path.join(curdir, file)
objects[label].append(path)
return objects
#讀取訓(xùn)練集數(shù)據(jù)
train_samples = \
search_file('../ml_data/speeches/training')
'''
2. 把所有類別為apple的mfcc合并在一起,形成訓(xùn)練集。
| mfcc | |
| mfcc | apple |
| mfcc | |
.....
由上述訓(xùn)練集樣本可以訓(xùn)練一個用于匹配apple的HMM。
'''
train_x, train_y = [], []
# 遍歷7次 apple/banana/...
for label, filenames in train_samples.items():
mfccs = np.array([])
for filename in filenames:
sample_rate, sigs = wf.read(filename)
mfcc = sf.mfcc(sigs, sample_rate)
if len(mfccs)==0:
mfccs = mfcc
else:
mfccs = np.append(mfccs, mfcc, axis=0)
train_x.append(mfccs)
train_y.append(label)
'''
訓(xùn)練集:
train_x train_y
----------------
| mfcc | |
| mfcc | apple |
| mfcc | |
----------------
| mfcc | |
| mfcc | banana |
| mfcc | |
-----------------
| mfcc | |
| mfcc | lime |
| mfcc | |
-----------------
'''
# {'apple':object, 'banana':object ...}
models = {}
for mfccs, label in zip(train_x, train_y):
model = hl.GaussianHMM(n_components=4,
covariance_type='diag', n_iter=1000)
models[label] = model.fit(mfccs)
'''
4. 讀取testing文件夾中的測試樣本,針對每一個測試樣本:
1. 分別使用7個HMM模型,對測試樣本計(jì)算score得分。
2. 取7個模型中得分最高的模型所屬類別作為預(yù)測類別。
'''
#讀取測試集數(shù)據(jù)
test_samples = \
search_file('../ml_data/speeches/testing')
test_x, test_y = [], []
for label, filenames in test_samples.items():
mfccs = np.array([])
for filename in filenames:
sample_rate, sigs = wf.read(filename)
mfcc = sf.mfcc(sigs, sample_rate)
if len(mfccs)==0:
mfccs = mfcc
else:
mfccs = np.append(mfccs, mfcc, axis=0)
test_x.append(mfccs)
test_y.append(label)
'''測試集:
test_x test_y
-----------------
| mfcc | apple |
-----------------
| mfcc | banana |
-----------------
| mfcc | lime |
-----------------
'''
pred_test_y = []
for mfccs in test_x:
# 判斷mfccs與哪一個HMM模型更加匹配
best_score, best_label = None, None
for label, model in models.items():
score = model.score(mfccs)
if (best_score is None) or (best_score<score):
best_score = score
best_label = label
pred_test_y.append(best_label)
print(test_y)
print(pred_test_y)
聲音合成
根據(jù)需求獲取某個聲音的模型頻域數(shù)據(jù),根據(jù)業(yè)務(wù)需要可以修改模型數(shù)據(jù),逆向生成時域數(shù)據(jù),完成聲音的合成。
案例:
import json
import numpy as np
import scipy.io.wavfile as wf
with open('../data/12.json', 'r') as f:
freqs = json.loads(f.read())
tones = [
('G5', 1.5),
('A5', 0.5),
('G5', 1.5),
('E5', 0.5),
('D5', 0.5),
('E5', 0.25),
('D5', 0.25),
('C5', 0.5),
('A4', 0.5),
('C5', 0.75)]
sample_rate = 44100
music = np.empty(shape=1)
for tone, duration in tones:
times = np.linspace(0, duration, duration * sample_rate)
sound = np.sin(2 * np.pi * freqs[tone] * times)
music = np.append(music, sound)
music *= 2 ** 15
music = music.astype(np.int16)
wf.write('../data/music.wav', sample_rate, music)
總結(jié)
以上所述是小編給大家介紹的Python實(shí)現(xiàn)語音識別和語音合成功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
- 關(guān)于Python調(diào)用百度語音合成SDK實(shí)現(xiàn)文字轉(zhuǎn)音頻的方法
- Python調(diào)用訊飛語音合成API接口來實(shí)現(xiàn)文字轉(zhuǎn)語音
- Python人工智能語音合成實(shí)現(xiàn)案例詳解
- Python語音合成的項(xiàng)目實(shí)戰(zhàn)(PyQt5+pyttsx3)
- 基于Python實(shí)現(xiàn)語音合成小工具
- 基于Python編寫一個語音合成系統(tǒng)
- Python實(shí)現(xiàn)語音合成功能詳解
- python3實(shí)現(xiàn)語音轉(zhuǎn)文字(語音識別)和文字轉(zhuǎn)語音(語音合成)
- python騰訊語音合成實(shí)現(xiàn)過程解析
- Python中edge-tts實(shí)現(xiàn)便捷語音合成
相關(guān)文章
python實(shí)現(xiàn)精準(zhǔn)搜索并提取網(wǎng)頁核心內(nèi)容
這篇文章主要為大家介紹了python實(shí)現(xiàn)精準(zhǔn)搜索并提取網(wǎng)頁核心內(nèi)容的實(shí)現(xiàn),有需要的的朋友可以借鑒參考下,希望能有所幫助祝大家多多進(jìn)步2021-11-11
python使用pywinauto驅(qū)動微信客戶端實(shí)現(xiàn)公眾號爬蟲
這個項(xiàng)目是通過pywinauto控制windows(win10)上的微信PC客戶端來實(shí)現(xiàn)公眾號文章的抓取。代碼分成server和client兩部分。server接收client抓取的微信公眾號文章,并且保存到數(shù)據(jù)庫。另外server支持簡單的搜索和導(dǎo)出功能。client通過pywinauto實(shí)現(xiàn)微信公眾號文章的抓取。2021-05-05
人工智能學(xué)習(xí)Pytorch教程Tensor基本操作示例詳解
這篇文章主要為大家介紹了人工智能學(xué)習(xí)Pytorch教程Tensor的基本操作示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-11-11
Python GUI編程之tkinter模塊Toplevel控件實(shí)現(xiàn)搭建父子窗口
這篇文章主要介紹了Python使用tkinter模塊Toplevel控件搭建父子窗口的實(shí)現(xiàn)方法,Tkinter是Python的標(biāo)準(zhǔn)GUI庫,Python使用Tkinter可以快速的創(chuàng)建GUI應(yīng)用程序,用到相關(guān)控件的同學(xué)可以參考下2023-12-12
python 環(huán)境變量和import模塊導(dǎo)入方法(詳解)
下面小編就為大家?guī)硪黄猵ython 環(huán)境變量和import模塊導(dǎo)入方法(詳解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-07-07
對Tensorflow中權(quán)值和feature map的可視化詳解
今天小編就為大家分享一篇對Tensorflow中權(quán)值和feature map的可視化詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06

