先来说下二进制读写文件,这需要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. 我想写一个前端开发工具(三):优化!从vue-cli学了几招

    我从过年开始写自己的前端工具 coodev,目前已经写出一个基本的架子,大多数预想的功能都能跑通,还剩一些需要解决的问题也都已经列出来了.本来这一周打算解决对不同后端模板的前后端渲染支持的问题.但是看 ...

  2. PHP实现数组递归转义的方法

    本文以实例形式讲述了PHP实现数组递归转义的方法,分享给大家供大家参考之用.具体方法如下: 主要功能代码如下: $arr = array('a"aa',array("c'd&quo ...

  3. css代码添加背景图片常用代码

    css代码添加背景图片常用代码 1 背景颜色 { font-size: 16px; content: ""; display: block; width: 700px; heigh ...

  4. unittest单元测试框架之unittest 框架的总结(七)

    1. Unittest 是 python 自带的单元测试框架,可以用其作为自动化框架来组织测试用例(测 试用例的执行顺序)的执行. 2. Unittest 框架的流程: 写好 TestCase 通过 ...

  5. direct path write 等待事件导致数据库hang

    同事反应十几分钟前数据库好像挂起了一会,让我排查数据库是否存在什么问题. 第一反应看当前数据库还是否有什么等待事件,结果有direct path write等待事件. 于是抓了问题时间段20分钟的AS ...

  6. var let const的一些区别

    var let const 都是来定义变量的. var let 作用域有些区别. const 类似于java中的常量的概念.即:只能给一个变量赋值一次,即指定一个引用. 举例来说: function ...

  7. JsonCpp在vs中使用

    Jsoncpp是c++生成和解析Json数据的跨平台开源库.下面简介如何在vs中使用. 1.官网下载.https://sourceforge.net/projects/jsoncpp/解压文件得到js ...

  8. pom.xml文件报MavenArchiver错误 org.apache.maven.archiver.MavenArchiver.getManifest(org.apache.maven.project.MavenProject, org.apache.maven.archiver.MavenArchiveConfiguration)

    第一种方式 war项目 <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId> ...

  9. 如何在tornado中以异步的方式调用同步函数

    问题 如何在tornado的coroutine中调用同步阻塞的函数 解决方案 使用python内置标准库的concurrent.futures.ThreadPoolExecutor和tornado.c ...

  10. obfuscator-llvm Theos 集成配置

    之前我写过一篇文章是关于在 Xcode 里怎么集成配置 obfuscator-llvmobfuscator-llvm Xcode集成配置 有些情况下我们使用 Theos 开发 tweak,需要将 ob ...