Python实现语音识别和语音合成
声音的本质是震动,震动的本质是位移关于时间的函数,波形文件(.wav)中记录了不同采样时刻的位移。
通过傅里叶变换,可以将时间域的声音函数分解为一系列不同频率的正弦函数的叠加,通过频率谱线的特殊分布,建立音频内容和文本的对应关系,以此作为模型训练的基础。
案例:画出语音信号的波形和频率分布,(freq.wav数据地址)
- # -*- 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个特殊频率所对应的能量分布,可以使用梅尔频率倒谱系数矩阵作为语音识别的特征。基于隐马尔科夫模型进行模式识别,找到测试样本最匹配的声音模型,从而识别语音内容。
MFCC
梅尔频率倒谱系数相关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()
隐马尔科夫模型
隐马尔科夫模型相关API:
- 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文件夹下的音频文件做分类
语音识别设计思路
1、读取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')
2、把所有类别为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)
3、训练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 ...}
4、读取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)
5、针对每一个测试样本:
1、分别使用7个HMM模型,对测试样本计算score得分。
2、取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)
Python实现语音识别和语音合成的更多相关文章
- ros下基于百度语音的,语音识别和语音合成
代码地址如下:http://www.demodashi.com/demo/13153.html 概述: 本demo是ros下基于百度语音的,语音识别和语音合成,能够实现文字转语音,语音转文字的功能. ...
- Python实时语音识别控制
代码地址如下:http://www.demodashi.com/demo/12946.html Python实时语音识别控制 概述 本文中的语音识别功能采用 百度语音识别库 ,首先利用 PyAudio ...
- Delphi百度语音【支持语音识别和语音合成】
作者QQ:(648437169) 点击下载➨百度语音 语音识别api文档 语音合成api文档 [Delphi 百度语音]支持获取 Access Token.语音识别.语 ...
- Python 百度语音识别与合成REST API及ffmpeg使用
操作系统:Windows Python:3.5 欢迎加入学习交流QQ群:657341423 百度语音识别官方文档 百度语音合成官方文档 注意事项:接口支持 POST 和 GET两种方式,个人支持用po ...
- Python简单语音识别并响应
起因是一个工作中喜欢说口头禅的同事,昨天老说"你看看你看看 操不操心".说了几次之后我就在他说完"你看看"后面续上,"操不操心".往复多次后 ...
- python +百度语音识别+图灵对话
https://github.com/Dongvdong/python_Smartvoice 上电后,只要周围声音超过 2000,开始录音5S 录音上传百度识别,并返回结果文字输出 继续等待,周围声音 ...
- python之语音识别(speech模块)
1.原理 语音操控分为 语音识别和语音朗读两部分. 这两部分本来是需要自然语言处理技能相关知识以及一系列极其复杂的算法才能搞定,可是这篇文章将会跳过此处,如果你只是对算法和自然语言学感兴趣的话,就只有 ...
- Python 语音识别
调用科大讯飞语音听写,使用Python实现语音识别,将实时语音转换为文字. 参考这篇博客实现的录音,首先在官网下载了关于语音听写的SDK,然后在文件夹内新建了两个.py文件,分别是get_audio. ...
- 语音识别中的CTC算法的基本原理解释
欢迎大家前往腾讯云+社区,获取更多腾讯海量技术实践干货哦~ 本文作者:罗冬日 目前主流的语音识别都大致分为特征提取,声学模型,语音模型几个部分.目前结合神经网络的端到端的声学模型训练方法主要CTC和基 ...
随机推荐
- leetcode bug free
---不包含jiuzhang ladders中出现过的题.如出现多个方法,则最后一个方法是最优解. 目录: 1 String 2 Two pointers 3 Array 4 DFS &&am ...
- Spring Cloud版本
Spring Cloud版本 Spring Cloud版本演进情况如下: 版本名称 版本 Finchley snapshot版 Edgware snapshot版 Dalston SR1 当前最新稳定 ...
- Javascript中将数字转换为中文的方法
//js实现将数字1234转化为汉字字符串(一千二百三十四)(或大写汉字壹仟贰佰叁拾肆): /*阿拉伯数字转中文数字 中文数字的特点: 每个计数数字都跟着一个权位,权位有:十.百.千.万.亿. 以“万 ...
- python骚操作---Print函数用法
---恢复内容开始--- python骚操作---Print函数用法 在 Python 中,print 可以打印所有变量数据,包括自定义类型. 在 3.x 中是个内置函数,并且拥有更丰富的功能. 参数 ...
- Apache性能测试工具ab使用详解~转载
Apache自带性能测试工具ab使用详解 一. Apache的下载 1. http://www.apache.org/,进入Apache的官网 2. 将页面拖到最下方“Apache Project L ...
- hive动态分区与静态分区
测试目的:1.分区表的动态分区与静态分区2.每层数据,数据流向,数据是否在每层都保留一份测试结果:1.动态分区/静态分区略2.每层表的数据都会保留,因此在生产上odm层的数据是可以删除的(不管是内表还 ...
- [HAOI2018]苹果树(组合数学,计数)
[HAOI2018]苹果树 cx巨巨给我的大火题. 感觉这题和上次考试gcz讲的那道有标号树的形态(不记顺序)计数问题很类似. 考虑如果对每个点对它算有贡献的其他点很麻烦,不知怎么下手.这个时候就想到 ...
- 解决mysql乱码
总结的几个乱码问题 希望我们全体学员也能够学会总结 java web 很是希望大家能够学好.并且也希望大家能够在学习过程中不段的积累相关的知识点 1.在response中写<meta http ...
- textRNN & textCNN的网络结构与代码实现!
1. 什么是textRNN textRNN指的是利用RNN循环神经网络解决文本分类问题,文本分类是自然语言处理的一个基本任务,试图推断出给定文本(句子.文档等)的标签或标签集合. 文本分类的应用非常广 ...
- ctpn+crnn 训练数据集生成
1. https://github.com/Belval/TextRecognitionDataGenerator 2. https://textrecognitiondatagenerator.re ...