AIRobot

AIRobot quick note


  • 首页

  • 关于

  • 标签

  • 分类

  • 归档

  • 搜索

读取wav文件绘制波形图

发表于 2019-01-02 分类于 Python
本文字数: 1.6k 阅读时长 ≈ 1 分钟
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# -*- coding: utf-8 -*-
import wave
import pylab as pl
import numpy as np
from pyaudio import PyAudio,paInt16

def record(filename):
#define of params
NUM_SAMPLES = 2000
framerate = 16000
channels = 1
sampwidth = 2
#record time
TIME = 10
def save_wave_file(filename, data):
'''save the date to the wav file'''
wf = wave.open(filename, 'wb')
wf.setnchannels(channels)
wf.setsampwidth(sampwidth)
wf.setframerate(framerate)
wf.writeframes("".join(data))
wf.close()

def record_wave():
#open the input of wave
pa = PyAudio()
stream = pa.open(format = paInt16, channels = 1,rate = framerate, input = True,frames_per_buffer = NUM_SAMPLES)
save_buffer = []
count = 0
while count < TIME*4:
#read NUM_SAMPLES sampling data
string_audio_data = stream.read(NUM_SAMPLES)
save_buffer.append(string_audio_data)
count += 1
print '.',
print ''
#filename = datetime.now().strftime("%Y-%m-%d_%H_%M_%S")+".wav"
save_wave_file(filename, save_buffer)
#save_buffer = []
#print filename, "saved"

record_wave()

def readwav(filename):
# 打开WAV文档
f = wave.open(filename, "rb")

# 读取格式信息
# (nchannels, sampwidth, framerate, nframes, comptype, compname)
params = f.getparams()
#print params
nchannels, sampwidth, framerate, nframes = params[:4]

# 读取波形数据
str_data = f.readframes(nframes)
f.close()

#将波形数据转换为数组
wave_data = np.fromstring(str_data, dtype=np.short)
#将数组转换为m行n列的数组,-1为自动计算长度
wave_data.shape = -1, nchannels
#print len(wave_data)
#矩阵倒置
wave_data = wave_data.T
#帧数×频率的倒数
time = np.arange(0, nframes) * (1.0 / framerate)

# 绘制波形
pl.subplot(211)
pl.plot(time, wave_data[0])
#第二声道
#pl.subplot(212)
#pl.plot(time, wave_data[1], c="g")
pl.xlabel("time (seconds)")
pl.show()

record("rectest.wav")
readwav("rectest.wav")
# Python
Python Excel openpyxl
线段树
AIRobot

AIRobot

AIRobot quick note
130 日志
15 分类
23 标签
GitHub E-Mail
Creative Commons
0%
© 2023 AIRobot | 716k | 10:51