欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python實(shí)現(xiàn)語音識(shí)別和語音合成功能

 更新時(shí)間:2019年09月20日 13:15:11   作者:凌逆戰(zhàn)  
聲音的本質(zhì)是震動(dòng),震動(dòng)的本質(zhì)是位移關(guān)于時(shí)間的函數(shù),波形文件(.wav)中記錄了不同采樣時(shí)刻的位移。這篇文章主要介紹了Python實(shí)現(xiàn)語音識(shí)別和語音合成,需要的朋友可以參考下

聲音的本質(zhì)是震動(dòng),震動(dòng)的本質(zhì)是位移關(guān)于時(shí)間的函數(shù),波形文件(.wav)中記錄了不同采樣時(shí)刻的位移。

通過傅里葉變換,可以將時(shí)間域的聲音函數(shù)分解為一系列不同頻率的正弦函數(shù)的疊加,通過頻率譜線的特殊分布,建立音頻內(nèi)容和文本的對(duì)應(yīng)關(guān)系,以此作為模型訓(xùn)練的基礎(chǔ)。

案例:畫出語音信號(hào)的波形和頻率分布,(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í)別

梅爾頻率倒譜系數(shù)(MFCC)通過與聲音內(nèi)容密切相關(guān)的13個(gè)特殊頻率所對(duì)應(yīng)的能量分布,可以使用梅爾頻率倒譜系數(shù)矩陣作為語音識(shí)別的特征?;陔[馬爾科夫模型進(jìn)行模式識(shí)別,找到測(cè)試樣本最匹配的聲音模型,從而識(shí)別語音內(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: 用幾個(gè)高斯分布函數(shù)擬合樣本數(shù)據(jù)
# covariance_type: 相關(guān)矩陣的輔對(duì)角線進(jìn)行相關(guān)性比較
# n_iter: 最大迭代上限
model.fit(mfccs) # 使用模型匹配測(cè)試mfcc矩陣的分值 score = model.score(test_mfccs)

案例:訓(xùn)練training文件夾下的音頻,對(duì)testing文件夾下的音頻文件做分類

1、讀取training文件夾中的訓(xùn)練音頻樣本,每個(gè)音頻對(duì)應(yīng)一個(gè)mfcc矩陣,每個(gè)mfcc都有一個(gè)類別(apple)。

2、把所有類別為apple的mfcc合并在一起,形成訓(xùn)練集。

  | mfcc |      |
  | mfcc | apple |
  | mfcc |      |
  .....
  由上述訓(xùn)練集樣本可以訓(xùn)練一個(gè)用于匹配apple的HMM。

3、訓(xùn)練7個(gè)HMM分別對(duì)應(yīng)每個(gè)水果類別。 保存在列表中。

4、讀取testing文件夾中的測(cè)試樣本,整理測(cè)試樣本

  | mfcc | apple |
  | mfcc | lime   |

5、針對(duì)每一個(gè)測(cè)試樣本:

  1、分別使用7個(gè)HMM模型,對(duì)測(cè)試樣本計(jì)算score得分。

  2、取7個(gè)模型中得分最高的模型所屬類別作為預(yù)測(cè)類別。

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)練音頻樣本,每個(gè)音頻對(duì)應(yīng)一個(gè)mfcc矩陣,每個(gè)mfcc都有一個(gè)類別(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對(duì)應(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)練一個(gè)用于匹配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文件夾中的測(cè)試樣本,針對(duì)每一個(gè)測(cè)試樣本:

   1. 分別使用7個(gè)HMM模型,對(duì)測(cè)試樣本計(jì)算score得分。

   2. 取7個(gè)模型中得分最高的模型所屬類別作為預(yù)測(cè)類別。

'''
#讀取測(cè)試集數(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)
​
'''測(cè)試集:
  test_x test_y
  -----------------
  | mfcc | apple |
  -----------------
  | mfcc | banana |
  -----------------
  | mfcc | lime  |
  -----------------
'''
pred_test_y = []
for mfccs in test_x:
# 判斷mfccs與哪一個(gè)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ù)需求獲取某個(gè)聲音的模型頻域數(shù)據(jù),根據(jù)業(yè)務(wù)需要可以修改模型數(shù)據(jù),逆向生成時(shí)域數(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)語音識(shí)別和語音合成功能,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!

相關(guān)文章

  • 淺析Python3中遍歷目錄的三種方法

    淺析Python3中遍歷目錄的三種方法

    在學(xué)習(xí)中,工作中,我們經(jīng)常會(huì)說遍歷一下當(dāng)前目錄咯,那么Python3中遍歷目錄的方法具體都有哪些呢并且如何操作呢,下面小編就來和大家簡(jiǎn)單聊聊吧
    2023-07-07
  • python實(shí)現(xiàn)精準(zhǔn)搜索并提取網(wǎng)頁核心內(nèi)容

    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ū)動(dòng)微信客戶端實(shí)現(xiàn)公眾號(hào)爬蟲

    python使用pywinauto驅(qū)動(dòng)微信客戶端實(shí)現(xiàn)公眾號(hào)爬蟲

    這個(gè)項(xiàng)目是通過pywinauto控制windows(win10)上的微信PC客戶端來實(shí)現(xiàn)公眾號(hào)文章的抓取。代碼分成server和client兩部分。server接收client抓取的微信公眾號(hào)文章,并且保存到數(shù)據(jù)庫。另外server支持簡(jiǎn)單的搜索和導(dǎo)出功能。client通過pywinauto實(shí)現(xiàn)微信公眾號(hào)文章的抓取。
    2021-05-05
  • python requests使用socks5的例子

    python requests使用socks5的例子

    今天小編就為大家分享一篇python requests使用socks5的例子,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07
  • 人工智能學(xué)習(xí)Pytorch教程Tensor基本操作示例詳解

    人工智能學(xué)習(xí)Pytorch教程Tensor基本操作示例詳解

    這篇文章主要為大家介紹了人工智能學(xué)習(xí)Pytorch教程Tensor的基本操作示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步
    2021-11-11
  • Python GUI編程之tkinter模塊Toplevel控件實(shí)現(xiàn)搭建父子窗口

    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)入方法(詳解)

    python 環(huán)境變量和import模塊導(dǎo)入方法(詳解)

    下面小編就為大家?guī)硪黄猵ython 環(huán)境變量和import模塊導(dǎo)入方法(詳解)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-07-07
  • 最大K個(gè)數(shù)問題的Python版解法總結(jié)

    最大K個(gè)數(shù)問題的Python版解法總結(jié)

    這篇文章主要介紹了最大K個(gè)數(shù)問題的Python版解法總結(jié),以最大K個(gè)數(shù)問題為基礎(chǔ)的算法題目在面試和各大考試及競(jìng)賽中經(jīng)常出現(xiàn),需要的朋友可以參考下
    2016-06-06
  • python圖形界面tkinter的使用技巧

    python圖形界面tkinter的使用技巧

    這篇文章主要介紹了python圖形界面tkinter的使用技巧,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下
    2022-09-09
  • 對(duì)Tensorflow中權(quán)值和feature map的可視化詳解

    對(duì)Tensorflow中權(quán)值和feature map的可視化詳解

    今天小編就為大家分享一篇對(duì)Tensorflow中權(quán)值和feature map的可視化詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-06-06

最新評(píng)論