Python實現語音識別和語音合成

聲音的本質是震動,震動的本質是位移關於時間的函數,波形文件(.wav)中記錄了不一樣採樣時刻的位移。python

經過傅里葉變換,能夠將時間域的聲音函數分解爲一系列不一樣頻率的正弦函數的疊加,經過頻率譜線的特殊分佈,創建音頻內容和文本的對應關係,以此做爲模型訓練的基礎。git

案例:畫出語音信號的波形和頻率分佈,(freq.wav數據地址github

# -*- 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()

語音識別

梅爾頻率倒譜系數(MFCC)經過與聲音內容密切相關的13個特殊頻率所對應的能量分佈,可使用梅爾頻率倒譜系數矩陣做爲語音識別的特徵。基於隱馬爾科夫模型進行模式識別,找到測試樣本最匹配的聲音模型,從而識別語音內容。json

MFCC

梅爾頻率倒譜系數相關API:app

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()

隱馬爾科夫模型

隱馬爾科夫模型相關API:url

import hmmlearn.hmm as hl

model = hl.GaussianHMM(n_components=4, covariance_type='diag', n_iter=1000)
# n_components: 用幾個高斯分佈函數擬合樣本數據
# covariance_type: 相關矩陣的輔對角線進行相關性比較
# n_iter: 最大迭代上限
model.fit(mfccs) # 使用模型匹配測試mfcc矩陣的分值 score = model.score(test_mfccs)

案例:訓練training文件夾下的音頻,對testing文件夾下的音頻文件作分類spa

語音識別設計思路

一、讀取training文件夾中的訓練音頻樣本,每一個音頻對應一個mfcc矩陣,每一個mfcc都有一個類別(apple)操作系統

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文件夾中的訓練音頻樣本,每一個音頻對應一個mfcc矩陣,每一個mfcc都有一個類別(apple...)。
def search_file(directory):
    """
    :param directory: 訓練音頻的路徑
    :return: 字典{'apple':[url, url, url ... ], 'banana':[...]}
    """
    # 使傳過來的directory匹配當前操做系統
    directory = os.path.normpath(directory)
    objects = {}
    # curdir:當前目錄
    # subdirs: 當前目錄下的全部子目錄
    # files: 當前目錄下的全部文件名
    for curdir, subdirs, files in os.walk(directory):
        for file in files:
            if file.endswith('.wav'):
                label = curdir.split(os.path.sep)[-1]   # os.path.sep爲路徑分隔符
                if label not in objects:
                    objects[label] = []
                # 把路徑添加到label對應的列表中
                path = os.path.join(curdir, file)
                objects[label].append(path)
    return objects


# 讀取訓練集數據
train_samples = search_file('../machine_learning_date/speeches/training')

二、把全部類別爲apple的mfcc合併在一塊兒,造成訓練集。

訓練集:

train_x:[mfcc1,mfcc2,mfcc3,...],[mfcc1,mfcc2,mfcc3,...]...

train_y:[apple],[banana]...

  由上述訓練集樣本能夠訓練一個用於匹配apple的HMM。

train_x, train_y = [], []
# 遍歷字典
for label, filenames in train_samples.items():
    # [('apple', ['url1,,url2...'])
    # [("banana"),("url1,url2,url3...")]...
    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)

三、訓練7個HMM分別對應每一個水果類別。 保存在列表中。

# 訓練模型,有7個句子,建立了7個模型
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)  # # {'apple':object, 'banana':object ...}

四、讀取testing文件夾中的測試樣本,整理測試樣本

  測試集數據:

  test_x: [mfcc1, mfcc2, mfcc3...]

  test_y :[apple, banana, lime]

# 讀取測試集數據
test_samples = search_file('../machine_learning_date/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)

五、針對每個測試樣本:
  一、分別使用7個HMM模型,對測試樣本計算score得分。
  二、取7個模型中得分最高的模型所屬類別做爲預測類別。

pred_test_y = []
for mfccs in test_x:
    # 判斷mfccs與哪個HMM模型更加匹配
    best_score, best_label = None, None
    # 遍歷7個模型
    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)   # ['apple', 'banana', 'kiwi', 'lime', 'orange', 'peach', 'pineapple']
print(pred_test_y)  # ['apple', 'banana', 'kiwi', 'lime', 'orange', 'peach', 'pineapple']

 

聲音合成

根據需求獲取某個聲音的模型頻域數據,根據業務須要能夠修改模型數據,逆向生成時域數據,完成聲音的合成。

案例,(數據集12.json地址):

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)
相關文章
相關標籤/搜索