声音的本质是震动,震动的本质是位移关于时间的函数,波形文件(.wav)中记录了不同采样时刻的位移。

通过傅里叶变换,可以将时间域的声音函数分解为一系列不同频率的正弦函数的叠加,通过频率谱线的特殊分布,建立音频内容和文本的对应关系,以此作为模型训练的基础。

案例:画出语音信号的波形和频率分布,(freq.wav数据地址

  1. # -*- encoding:utf-8 -*-
  2. import numpy as np
  3. import numpy.fft as nf
  4. import scipy.io.wavfile as wf
  5. import matplotlib.pyplot as plt
  6.  
  7. sample_rate, sigs = wf.read('../machine_learning_date/freq.wav')
  8. print(sample_rate) # 8000采样率
  9. print(sigs.shape) # (3251,)
  10. sigs = sigs / (2 ** 15) # 归一化
  11. times = np.arange(len(sigs)) / sample_rate
  12. freqs = nf.fftfreq(sigs.size, 1 / sample_rate)
  13. ffts = nf.fft(sigs)
  14. pows = np.abs(ffts)
  15. plt.figure('Audio')
  16. plt.subplot(121)
  17. plt.title('Time Domain')
  18. plt.xlabel('Time', fontsize=12)
  19. plt.ylabel('Signal', fontsize=12)
  20. plt.tick_params(labelsize=10)
  21. plt.grid(linestyle=':')
  22. plt.plot(times, sigs, c='dodgerblue', label='Signal')
  23. plt.legend()
  24. plt.subplot(122)
  25. plt.title('Frequency Domain')
  26. plt.xlabel('Frequency', fontsize=12)
  27. plt.ylabel('Power', fontsize=12)
  28. plt.tick_params(labelsize=10)
  29. plt.grid(linestyle=':')
  30. plt.plot(freqs[freqs >= 0], pows[freqs >= 0], c='orangered', label='Power')
  31. plt.legend()
  32. plt.tight_layout()
  33. plt.show()

语音识别

梅尔频率倒谱系数(MFCC)通过与声音内容密切相关的13个特殊频率所对应的能量分布,可以使用梅尔频率倒谱系数矩阵作为语音识别的特征。基于隐马尔科夫模型进行模式识别,找到测试样本最匹配的声音模型,从而识别语音内容。

MFCC

梅尔频率倒谱系数相关API:

  1. import scipy.io.wavfile as wf
  2. import python_speech_features as sf

  3. sample_rate, sigs = wf.read('../data/freq.wav')
  4. mfcc = sf.mfcc(sigs, sample_rate)

案例:画出MFCC矩阵:

python -m pip install python_speech_features

  1. import scipy.io.wavfile as wf
  2. import python_speech_features as sf
  3. import matplotlib.pyplot as mp

  4. sample_rate, sigs = wf.read(
  5. '../ml_data/speeches/training/banana/banana01.wav')
  6. mfcc = sf.mfcc(sigs, sample_rate)

  7. mp.matshow(mfcc.T, cmap='gist_rainbow')
  8. mp.show()

隐马尔科夫模型

隐马尔科夫模型相关API:

  1. import hmmlearn.hmm as hl
  2.  
  3. model = hl.GaussianHMM(n_components=4, covariance_type='diag', n_iter=1000)
  4. # n_components: 用几个高斯分布函数拟合样本数据
  5. # covariance_type: 相关矩阵的辅对角线进行相关性比较
  6. # n_iter: 最大迭代上限
  7. model.fit(mfccs) # 使用模型匹配测试mfcc矩阵的分值 score = model.score(test_mfccs)

案例:训练training文件夹下的音频,对testing文件夹下的音频文件做分类

语音识别设计思路

1、读取training文件夹中的训练音频样本,每个音频对应一个mfcc矩阵,每个mfcc都有一个类别(apple)

  1. import os
  2. import numpy as np
  3. import scipy.io.wavfile as wf
  4. import python_speech_features as sf
  5. import hmmlearn.hmm as hl
  6.  
  7. # 1. 读取training文件夹中的训练音频样本,每个音频对应一个mfcc矩阵,每个mfcc都有一个类别(apple...)。
  8. def search_file(directory):
  9. """
  10. :param directory: 训练音频的路径
  11. :return: 字典{'apple':[url, url, url ... ], 'banana':[...]}
  12. """
  13. # 使传过来的directory匹配当前操作系统
  14. directory = os.path.normpath(directory)
  15. objects = {}
  16. # curdir:当前目录
  17. # subdirs: 当前目录下的所有子目录
  18. # files: 当前目录下的所有文件名
  19. for curdir, subdirs, files in os.walk(directory):
  20. for file in files:
  21. if file.endswith('.wav'):
  22. label = curdir.split(os.path.sep)[-1] # os.path.sep为路径分隔符
  23. if label not in objects:
  24. objects[label] = []
  25. # 把路径添加到label对应的列表中
  26. path = os.path.join(curdir, file)
  27. objects[label].append(path)
  28. return objects
  29.  
  30. # 读取训练集数据
  31. train_samples = search_file('../machine_learning_date/speeches/training')

2、把所有类别为apple的mfcc合并在一起,形成训练集。

训练集:

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

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

  由上述训练集样本可以训练一个用于匹配apple的HMM。

  1. train_x, train_y = [], []
  2. # 遍历字典
  3. for label, filenames in train_samples.items():
  4. # [('apple', ['url1,,url2...'])
  5. # [("banana"),("url1,url2,url3...")]...
  6. mfccs = np.array([])
  7. for filename in filenames:
  8. sample_rate, sigs = wf.read(filename)
  9. mfcc = sf.mfcc(sigs, sample_rate)
  10. if len(mfccs) == 0:
  11. mfccs = mfcc
  12. else:
  13. mfccs = np.append(mfccs, mfcc, axis=0)
  14. train_x.append(mfccs)
  15. train_y.append(label)

3、训练7个HMM分别对应每个水果类别。 保存在列表中。

  1. # 训练模型,有7个句子,创建了7个模型
  2. models = {}
  3. for mfccs, label in zip(train_x, train_y):
  4. model = hl.GaussianHMM(n_components=4, covariance_type='diag', n_iter=1000)
  5. models[label] = model.fit(mfccs) # # {'apple':object, 'banana':object ...}

4、读取testing文件夹中的测试样本,整理测试样本

  测试集数据:

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

  test_y :[apple, banana, lime]

  1. # 读取测试集数据
  2. test_samples = search_file('../machine_learning_date/speeches/testing')
  3.  
  4. test_x, test_y = [], []
  5. for label, filenames in test_samples.items():
  6. mfccs = np.array([])
  7. for filename in filenames:
  8. sample_rate, sigs = wf.read(filename)
  9. mfcc = sf.mfcc(sigs, sample_rate)
  10. if len(mfccs) == 0:
  11. mfccs = mfcc
  12. else:
  13. mfccs = np.append(mfccs, mfcc, axis=0)
  14. test_x.append(mfccs)
  15. test_y.append(label)

5、针对每一个测试样本:
  1、分别使用7个HMM模型,对测试样本计算score得分。
  2、取7个模型中得分最高的模型所属类别作为预测类别。

  1. pred_test_y = []
  2. for mfccs in test_x:
  3. # 判断mfccs与哪一个HMM模型更加匹配
  4. best_score, best_label = None, None
  5. # 遍历7个模型
  6. for label, model in models.items():
  7. score = model.score(mfccs)
  8. if (best_score is None) or (best_score < score):
  9. best_score = score
  10. best_label = label
  11. pred_test_y.append(best_label)
  12.  
  13. print(test_y) # ['apple', 'banana', 'kiwi', 'lime', 'orange', 'peach', 'pineapple']
  14. print(pred_test_y) # ['apple', 'banana', 'kiwi', 'lime', 'orange', 'peach', 'pineapple']

声音合成

根据需求获取某个声音的模型频域数据,根据业务需要可以修改模型数据,逆向生成时域数据,完成声音的合成。

案例,(数据集12.json地址):

  1. import json
  2. import numpy as np
  3. import scipy.io.wavfile as wf
  4. with open('../data/12.json', 'r') as f:
  5. freqs = json.loads(f.read())
  6. tones = [
  7. ('G5', 1.5),
  8. ('A5', 0.5),
  9. ('G5', 1.5),
  10. ('E5', 0.5),
  11. ('D5', 0.5),
  12. ('E5', 0.25),
  13. ('D5', 0.25),
  14. ('C5', 0.5),
  15. ('A4', 0.5),
  16. ('C5', 0.75)]
  17. sample_rate = 44100
  18. music = np.empty(shape=1)
  19. for tone, duration in tones:
  20. times = np.linspace(0, duration, duration * sample_rate)
  21. sound = np.sin(2 * np.pi * freqs[tone] * times)
  22. music = np.append(music, sound)
  23. music *= 2 ** 15
  24. music = music.astype(np.int16)
  25. wf.write('../data/music.wav', sample_rate, music)

Python实现语音识别和语音合成的更多相关文章

  1. ros下基于百度语音的,语音识别和语音合成

    代码地址如下:http://www.demodashi.com/demo/13153.html 概述: 本demo是ros下基于百度语音的,语音识别和语音合成,能够实现文字转语音,语音转文字的功能. ...

  2. Python实时语音识别控制

    代码地址如下:http://www.demodashi.com/demo/12946.html Python实时语音识别控制 概述 本文中的语音识别功能采用 百度语音识别库 ,首先利用 PyAudio ...

  3. Delphi百度语音【支持语音识别和语音合成】

    作者QQ:(648437169) 点击下载➨百度语音         语音识别api文档         语音合成api文档 [Delphi 百度语音]支持获取 Access Token.语音识别.语 ...

  4. Python 百度语音识别与合成REST API及ffmpeg使用

    操作系统:Windows Python:3.5 欢迎加入学习交流QQ群:657341423 百度语音识别官方文档 百度语音合成官方文档 注意事项:接口支持 POST 和 GET两种方式,个人支持用po ...

  5. Python简单语音识别并响应

    起因是一个工作中喜欢说口头禅的同事,昨天老说"你看看你看看 操不操心".说了几次之后我就在他说完"你看看"后面续上,"操不操心".往复多次后 ...

  6. python +百度语音识别+图灵对话

    https://github.com/Dongvdong/python_Smartvoice 上电后,只要周围声音超过 2000,开始录音5S 录音上传百度识别,并返回结果文字输出 继续等待,周围声音 ...

  7. python之语音识别(speech模块)

    1.原理 语音操控分为 语音识别和语音朗读两部分. 这两部分本来是需要自然语言处理技能相关知识以及一系列极其复杂的算法才能搞定,可是这篇文章将会跳过此处,如果你只是对算法和自然语言学感兴趣的话,就只有 ...

  8. Python 语音识别

    调用科大讯飞语音听写,使用Python实现语音识别,将实时语音转换为文字. 参考这篇博客实现的录音,首先在官网下载了关于语音听写的SDK,然后在文件夹内新建了两个.py文件,分别是get_audio. ...

  9. 语音识别中的CTC算法的基本原理解释

    欢迎大家前往腾讯云+社区,获取更多腾讯海量技术实践干货哦~ 本文作者:罗冬日 目前主流的语音识别都大致分为特征提取,声学模型,语音模型几个部分.目前结合神经网络的端到端的声学模型训练方法主要CTC和基 ...

随机推荐

  1. leetcode bug free

    ---不包含jiuzhang ladders中出现过的题.如出现多个方法,则最后一个方法是最优解. 目录: 1 String 2 Two pointers 3 Array 4 DFS &&am ...

  2. Spring Cloud版本

    Spring Cloud版本 Spring Cloud版本演进情况如下: 版本名称 版本 Finchley snapshot版 Edgware snapshot版 Dalston SR1 当前最新稳定 ...

  3. Javascript中将数字转换为中文的方法

    //js实现将数字1234转化为汉字字符串(一千二百三十四)(或大写汉字壹仟贰佰叁拾肆): /*阿拉伯数字转中文数字 中文数字的特点: 每个计数数字都跟着一个权位,权位有:十.百.千.万.亿. 以“万 ...

  4. python骚操作---Print函数用法

    ---恢复内容开始--- python骚操作---Print函数用法 在 Python 中,print 可以打印所有变量数据,包括自定义类型. 在 3.x 中是个内置函数,并且拥有更丰富的功能. 参数 ...

  5. Apache性能测试工具ab使用详解~转载

    Apache自带性能测试工具ab使用详解 一. Apache的下载 1. http://www.apache.org/,进入Apache的官网 2. 将页面拖到最下方“Apache Project L ...

  6. hive动态分区与静态分区

    测试目的:1.分区表的动态分区与静态分区2.每层数据,数据流向,数据是否在每层都保留一份测试结果:1.动态分区/静态分区略2.每层表的数据都会保留,因此在生产上odm层的数据是可以删除的(不管是内表还 ...

  7. [HAOI2018]苹果树(组合数学,计数)

    [HAOI2018]苹果树 cx巨巨给我的大火题. 感觉这题和上次考试gcz讲的那道有标号树的形态(不记顺序)计数问题很类似. 考虑如果对每个点对它算有贡献的其他点很麻烦,不知怎么下手.这个时候就想到 ...

  8. 解决mysql乱码

    总结的几个乱码问题 希望我们全体学员也能够学会总结 java web 很是希望大家能够学好.并且也希望大家能够在学习过程中不段的积累相关的知识点 1.在response中写<meta  http ...

  9. textRNN & textCNN的网络结构与代码实现!

    1. 什么是textRNN textRNN指的是利用RNN循环神经网络解决文本分类问题,文本分类是自然语言处理的一个基本任务,试图推断出给定文本(句子.文档等)的标签或标签集合. 文本分类的应用非常广 ...

  10. ctpn+crnn 训练数据集生成

    1. https://github.com/Belval/TextRecognitionDataGenerator 2. https://textrecognitiondatagenerator.re ...