Python--pyaudio声卡录音

1、关于pyaudio的使用,请参看前一篇博文:

Python--pyAudio播放wav格式声音: http://blog.csdn.net/xsc_c/article/details/8944077


2、关于wav文件的操作,参看博文:

Python--读取wav格式文件: http://blog.csdn.net/xsc_c/article/details/8941338


3、录音的过程与播放使用的函数类似,可以参考使用手册:

API文档地址 : http://people.csail.mit.edu/hubert/pyaudio/docs/#class-pyaudio


4、python代码

#!usr/bin/env python
#coding=utf-8

import numpy as np
from pyaudio import PyAudio,paInt16
from datetime import datetime
import wave
from Tkinter import *

#define of params
NUM_SAMPLES = 2000
framerate = 8000
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 my_button(root,label_text,button_text,button_func):  
    '''''function of creat label and button'''  
    #label details  
    label = Label(root)  
    label['text'] = label_text  
    label.pack()  
    #label details  
    button = Button(root)  
    button['text'] = button_text  
    button['command'] = button_func  
    button.pack()	
	
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 '.'

	filename = datetime.now().strftime("%Y-%m-%d_%H_%M_%S")+".wav"
	save_wave_file(filename, save_buffer)
	save_buffer = []
	print filename, "saved"

def main():
	root = Tk()
	my_button(root,"Record a wave","clik to record",record_wave)
	root.mainloop()
	
if __name__ == "__main__":
	main()

5、效果

界面:


保存文件:


评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值