先来说下二进制读写文件,这需要struct库

#二进制文件读写
import struct
a=
b=-
# print(struct.pack("h",b))
# print(struct.pack("i",b)) f=open("bbb.bin","wb")
f.write(struct.pack("h",a))#对a装包,并写入
f.write(struct.pack("h",b))
f.close() f=open("bbb.bin",'rb')
b1=f.read()
a=struct.unpack("h",b1)#解包操作
b2=f.read()
b=struct.unpack("h",b2)
print(a,b)

然后是通过python创造一段声音

import wave
import math
import struct
f=wave.open("v0.wav","w")
f.setframerate(8000)#声音频率
f.setnchannels(1)#声道数
f.setsampwidth(2)#声音宽度
t=0#时间
v=0.5#音量
dt=1/8000.0#录入声音的时间 while t<5:
s=math.sin(t*math.pi*2*800)*v*32768#设置声音频率为-32768到32768,并且为正弦变化曲线
s=int(s)
fd=struct.pack("h",s)#二进制写入
f.writeframes(fd)
t+=dt
f.close()

运用这个原理可以写一个简单的声音文件,比如说两只老虎

import wave
import math
import struct
ff=wave.open("v1.wav","w")
ff.setframerate(8000)
ff.setnchannels(1)
ff.setsampwidth(2) def wv(t=0,f=0,v=0.5,wf=ff,sr=8000):
'''
t:写入时长
f:声音频率
v:音量
wf:一个可以写入的音频文件
sr:采样率
'''
tt=0
dt=1.0/sr
while tt<=t:
s=math.sin(tt*math.pi*2*f)*v*32768#采样,调节音量,映射到[-2^15,2^15)
s=int(s) fd=struct.pack("h",s)#转换成8bit二进制数据
wf.writeframes(fd)#写入音频文件
tt+=dt#时间流逝 note={"":262,"":294,"":330,"":349,"":392,"":440,"":494,"6-":220,"":0}
n=[
"","","","","","","","","",
"","","","","","","","",
"","","","","","","","","","","","","","",
"","6-","","","","6-",""
]
tm=[
2,2,2,2,2,2,2,2,1,
2,2,2,1.5,2,2,2,2,
1,1,1,1,2,2,1,1,1,1,1,1,2,1,
2,2,2,2,2,2,2
] for i in range(len(n)):
wv(tm[i]/4.0,note[n[i]]) ff.close()
#河大校歌
import wave
import math
import struct
ff=wave.open("henu.wav","w")
ff.setframerate(8000)
ff.setnchannels(1)
ff.setsampwidth(2) ff.getsampwidth def wv(t=0,f=0,v=0.5,wf=ff,sr=8000):
'''
t:写入时长
f:声音频率
v:音量
wf:一个可以写入的音频文件
sr:采样率
'''
tt=0
dt=1.0/sr
while tt<=t:
s=math.sin(tt*math.pi*2*f)*v*math.pow(math.e,-2.5*tt)*32768#采样,调节音量,映射到[-2^15,2^15)
s=int(s) fd=struct.pack("h",s)#转换成8bit二进制数据
wf.writeframes(fd)#写入音频文件
tt+=dt#时间流逝 note={"-":0,"":0,"1---":49,"1#---":52,"2b---":52,"2---":55,"2#---":58,"3b---":58,"3---":62,"4---":65,"4#---":69,"5b---":69,"5---":73,"5#---":78,"6b---":78,"6---":82,"6#---":87,"7b---":87,"7---":92,"1--":98,"1#--":104,"2b--":104,"2--":110,"2#--":117,"3b--":117,"3--":123,"4--":131,"4#--":139,"5b--":139,"5--":147,"5#--":156,"6b--":156,"6--":165,"6#--":175,"7b--":175,"7--":185,"1-":196,"1#-":208,"2b-":208,"2-":220,"2#-":233,"3b-":233,"3-":247,"4-":262,"4#-":277,"5b-":277,"5-":294,"5#-":311,"6b-":311,"6-":330,"6#-":349,"7b-":349,"7-":370,"":392,"1#":415,"2b":415,"":440,"2#":466,"3b":466,"":494,"":523,"4#":554,"5b":554,"":587,"5#":622,"6b":622,"":659,"6#":698,"7b":698,"":740,"1+":784,"1#+":831,"2b+":831,"2+":880,"2#+":932,"3b+":932,"3+":988,"4+":1047,"4#+":1109,"5b+":1109,"5+":1175,"5#+":1245,"6b+":1245,"6+":1319,"6#+":1397,"7b+":1397,"7+":1480,"1++":1568,"1#++":1661,"2b++":1661,"2++":1760,"2#++":1865,"3b++":1865,"3++":1976,"4++":2093,"4#++":2217,"5b++":2217,"5++":2349,"5#++":2489,"6b++":2489} n=[
"5-","","","","7-",
"","","","","",
"","","","",
"","","","-",
"","","","7-","6-",
"7-","","","","",
"","","","",
"","","","","-",
"","","","",
"","","","","",
"","","","",
"","","","7-","5-",
"","","","","","-",
"","","","-",
"","","","","","-",
"6-","7-","","-"
]
tm=[
2,2,2,1,1,
2,2,2,1,1,
3,1,2,2,
2,2,2,2,
3,1,1,1,2,
3,1,1,1,2,
2,2,2,2,
2,1,1,2,2,
3,1,2,2,
3,1,1,1,2,
2,2,2,2,
3,1,1,1,2,
1,1,1,1,2,2,
2,2,2,2,
1,1,1,1,2,2,
3,1,3,4
] for i in range(len(n)):
wv(tm[i]/2.0,note[n[i]]) ff.close()

接下来是比较高级的了,显示声音的音波

import matplotlib.pyplot as plt
import wave
import struct fig=plt.figure()
ax=fig.add_subplot(1,1,1)#如果参数是349的意思是:将画布分割成3行4列,图像画在从左到右从上到下的第9块
plt.ion()#使matplotlib的显示模式转换为交互(interactive)模式。即使在脚本中遇到plt.show(),代码还是会继续执行。
read_size=200#每次绘画的帧数
pass_f=0#跳过前pass的帧数
draw_channel=0
stay_time=1.0 file=wave.open("henu.wav","r") frame_rate=file.getframerate()
frames = file.getnframes()#得到频率
channels=file.getnchannels()#得到声道数
draw_channel=draw_channel %channels
i=0
x_data=[x / read_size for x in range(read_size)]
fmt="h" * (read_size * channels) while i<frames:
fs=file.readframes(read_size)
i+=read_size
if pass_f > 0:
pass_f-=1
continue
f_data = struct .unpack(fmt,fs) # f_data中包含多个声道的声音
y_data =[]
for j in range(0,len(f_data)):
if j%channels==draw_channel:
y_data.append(f_data[j]/32768.0)
lines = ax.plot(x_data, y_data, 'g-', lw=1)
plt.pause(stay_time)
ax.lines.remove(lines[0])
file.close()

这个是拟合一个图像的曲线,机器学习????

#训练一个多项式,来拟合一条曲线
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
import random
import math
import tensorflow as tf pix2=math.pi*2 img=np.array(Image.open("./p2.bmp"),dtype=np.int32)
#(249, 277, 3)图像的 高度,宽度,通道rgb
#Y中点125
data=[]
a=img[:,:,0]+img[:,:,1]+img[:,:,2]
h,w,_=np.shape(img)
nw=-1
for j in range(w):
for i in range(h):
if a[i,j]<200:
data.append([j*1.0/w,(125.0-i)*2.0/w])
if j%13==0 and nw!=j:
nw=j
data_len=len(data)
#y=a1*sin(2pix*b1)+a2*sin(2pix*b2)+a3*sin(2pix*b3)... #画图
fig=plt.figure()#生成图像框
ax=fig.add_subplot(1,1,1)#编号
ax.scatter([ w[0] for w in data],[w[1] for w in data],linewidths=1)
plt.ion()
#######################################################
#模型
w_size=8
batch_size=64 x=tf.placeholder(dtype=tf.float32, shape=[None,1])
y=tf.placeholder(dtype=tf.float32, shape=[None,1])
w=tf.Variable(tf.truncated_normal(shape=[w_size,1],mean=0.0,stddev=2/w_size,dtype=tf.float32))
#c=tf.constant([[(i+1)*2*math.pi for i in range(w_size)]],tf.float32)
c=tf.Variable(tf.constant([[(i+1)*2*math.pi for i in range(w_size)]],tf.float32))
res=tf.matmul(tf.sin(tf.matmul(x,c)),w)
loss=tf.reduce_mean(tf.abs((res-y))) train_step=tf.train.AdamOptimizer(0.02).minimize(loss)
init=tf.global_variables_initializer()
sess=tf.Session()
sess.run(init)
for i in range(1,10000):
rnddata=[random.randint(1,data_len-1) for w in range(batch_size)]
x_d=[[data[p][0]] for p in rnddata]
y_d=[[data[p][1]] for p in rnddata]
ls,st=sess.run([loss,train_step],feed_dict={x:x_d,y:y_d})
print(i,":",ls) if i%100==0:
x_data=[[j/500.0] for j in range(500)]
y_data,ww,cc=sess.run([res,w,c],feed_dict={x:x_data})
print(ww)
print(cc)
lines=ax.plot([j[0] for j in x_data],[j[0] for j in y_data],'r-',lw=1)
plt.pause(1)
ax.lines.remove(lines[0])

最后是你输入文字然后让它发音,前提是你要有汉字表和发音表

t2pinyin={}
yunmu="āáǎàōóǒòēéěèīíǐìūúǔùǖǘǚǜ"
yindiao="123412341234123412341234"
rp="aaaaooooeeeeiiiiuuuuvvvv"
for i in range(1,10):#总共有十个文件,循环打开
fn="./pinyin1/h"+str(i)+".txt"
py=open(fn,"r",encoding="utf-8")#打开文件名 只读 utf-8
line1=py.readline() #读取一行,再次调用就是下一行,先把第一行文字读进来
line2="" #读拼音
while len(line2)<=10:#查找哪一行是拼音
line2=py.readline()
line1=line1.replace("\n","")#替换换行
line2=line2.replace("\n","").replace("ü","v")
py.close()
pinyin=line2.split(" ")#变换成列表 for j in range(len(line1)):
word=line1[j]#word和pyj照应
pyj=pinyin[j]
flag=0
for k in range(24):
if pyj.find(yunmu[k])>=0:#查找拼音里的韵母
pyj=pyj.replace(yunmu[k],rp[k])+yindiao[k]#替换,并标记声调
flag=1
break
if flag==0:#没找到就是轻声
pyj=pyj+"0"
t2pinyin[word] = pyj
print(t2pinyin["大"],t2pinyin["家"],t2pinyin["好"]) s="我在学拍森"
import wave
wf=wave.open("py.wav","w")
wf.setframerate(16000)#设置频率的最大值
wf.setnchannels(2)#设置声道数
wf.setsampwidth(2)#设置声音宽度 for w in s:
if w in t2pinyin:#找s中的每个字的读音
vv=t2pinyin[w]
file_name = "./pinyin/" + vv + ".wav"
speak_file=wave.open(file_name,"r")
data=speak_file.readframes(100000000)#将该文件下的前100000000个频率赋值给data
wf.writeframes(data)
speak_file.close()
wf.close()

python3-声音处理的更多相关文章

  1. python3——模块

    今天去听一个关于创业的讲座,心疼自己在那个地方站了 一个多小时(QAQ)我是心疼自己傻呀! 手机打王者之后就没有电了,一直站在那儿! 不过最后还是结束了,以后你们也会有很多讲座的,希望学弟学妹好好听讲 ...

  2. python3 - 文本读音器

    本篇分享的是使用python3制作一个文本读音器,简单点就是把指定的文本文字转语音说出来:做这么个小工具主要是为了方便自己在平时看一些文章眼累的时候,可通过语音来帮助自己,当然如果你是小说迷,可以扩展 ...

  3. 从零开始学习PYTHON3讲义(十五)让画面动起来

    <从零开始PYTHON3>第十五讲 虽然看起来绘图和音乐并不相关,但是听过了上一讲的内容你一定知道,这是游戏编程中四个需要处理内容的两部分,这两部分必须同时.并行的处理,不能因为某一项计算 ...

  4. 从零开始学习PYTHON3讲义(十四)写一个mp3播放器

    <从零开始PYTHON3>第十四讲 通常来说,Python解释执行,运行速度慢,并不适合完整的开发游戏.随着电脑速度的快速提高,这种情况有所好转,但开发游戏仍然不是Python的重点工作. ...

  5. 从零开始学习PYTHON3讲义(九)字典类型和插入排序

    <从零开始PYTHON3>第九讲 第六讲.上一讲我们都介绍了列表类型.列表类型是编程中最常用的一种类型,但也有挺明显的缺陷,比如: data = [5,22,34,12,87,67,3,4 ...

  6. Python3 标准库学习

    python3.5.6 官方文档  https://docs.python.org/3.5/library/index.html 1.介绍 2.内置函数 3.内置常量 3.1常数添加的 site模块 ...

  7. python3 第三十一章 - 模块

    1.什么是模块 如果从Python解释器退出并再次输入,您所做的定义(函数和变量)将丢失.因此,如果要编写一个稍长的程序,最好使用文本编辑器为解释器准备输入,并以该文件作为输入运行它.这称为创建脚本. ...

  8. Python3语法详解

    一.下载安装 1.1Python下载 Python官网:https://www.python.org/ 1.2Python安装 1.2.1 Linux 平台安装 以下为在Unix & Linu ...

  9. python基础系列教程——Python3.x标准模块库目录

    python基础系列教程——Python3.x标准模块库目录 文本 string:通用字符串操作 re:正则表达式操作 difflib:差异计算工具 textwrap:文本填充 unicodedata ...

  10. Python3 函数式编程自带函数

    一 map函数 引子 需求1:num1=[1,2,3,4],我的需求是把num1中的每个元素平方后组成新列表. ret = [] num1 = [1,2,3,4] for i in num1: ret ...

随机推荐

  1. android 下使用Direct Texture

    要使用Direct Texture,需要有一份android系统的源码 部分C++代码如下: #include <stdio.h> #include <stdlib.h> #i ...

  2. mobBUS

    1.今天听陈刚说起modBUS通信协议,这个还是第一次听说,究竟是什么东东,还是上网查查看吧 2.网上有C语言程序. http://blog.163.com/li_g888@126/blog/stat ...

  3. JS其他类型值转化为Boolean类型规则

    由于最近在笔试的时候,发现好多关于其他类型转化为Boolean类型的题目,因此总结一下! 一.String类型转化为Boolean 1.转化结果为true的情况 ①任何非空字符串 PS:空白字符串也是 ...

  4. unittest单元测试框架之unittest工作原理(一)

    1.Unittest 核心组件 test case.test suite.test runner.test fixture 2.unittest 静态图 Testcase:一个 testcase 就是 ...

  5. java中匿名内部类总结

    在java的世界里,提供了匿名内部类语法糖,用于帮助大家简化代码,本文简要从接口,抽象类以及常规类以代码的形式描述其常用模式. 1. 接口模式 public interface IWriter { v ...

  6. 协作开发中常用的Git命令小结

    先提一下最基础的git命令用法: git clone   从远端克隆到本地仓库 git add . (注意add和. 之间有一个空格)将全部改动添加到暂存区 git checkout xxx 撤销更改 ...

  7. Redis与Python进行交互

    安装包 安装Redis的有3种方式https://github.com/andymccurdy/redis-py 第一种:进⼊虚拟环境,联⽹安装包redis pip install redis 第二种 ...

  8. 如何让tomcat服务器运行在80端口,并且无需输入项目名即可访问项目()

    这个问题最开始遇到的时候是半年前,自己买了个服务器玩,但是域名解析的时候出了问题,我查了查资料才知道腾讯云是默认解析到80端口,而且还改不了. 首先是修改tomcat运行端口号,默认是8080,但是我 ...

  9. TinyMCE:下载、安装、配置

    第一步:下载 官网下载:https://www.tiny.cloud/download/ TinyMCE从4.0开始,不再支持直接下载,而是直接使用提供免费的CDN,让用户免除安装过程,可以在网站中使 ...

  10. node.js使用Sequelize 操作mysql

    Sequelize就是Node上的ORM框架 ,相当于java端的Hibernate 是一个基于 promise 的 Node.js ORM, 目前支持 Postgres, MySQL, SQLite ...