python-利用pyaudio进行声音录制及简单实例代码分享

一、关于pyaudio的安装

现在pyaudio的版本为:PyAudio v0.2.9,若想安装其他版本,请参考以下链接:http://people.csail.mit.edu/hubert/pyaudio/packages/
1、Windows 用户:
通过pip安装:
python -m pip install pyaudio
2、Mac OS X 用户:
利用Homebrew安装portaudio,然后通过pip安装pyaudio:
brew install portaudio
pip install pyaudio

没有安装过Homebrew的用户可通过在终端中输入:ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" 进行安装,若有相关疑问可参考以下链接:http://brew.sh(Homebrew和Pyaudio的安装需要事先安装过Xcode的ComandLineTools)
相关链接:http://people.csail.mit.edu/hubert/pyaudio/#downloads

二、关于pyaudio的使用


为方便大家,列举简单的播放录制的使用方法,这些代码在以上的链接里均可找到,同时还有其他的一些功能的代码实例,在这里我不一一列举。


Play


"""PyAudio Example: Play a WAVE file."""
import pyaudio
import wave
import sys
CHUNK = 1024
if len(sys.argv) < 2:
    print("Plays a wave file.\n\nUsage: %s filename.wav" % sys.argv[0])
    sys.exit(-1)
wf = wave.open(sys.argv[1], 'rb')
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),channels=wf.getnchannels(),rate=wf.getframerate(),output=True)
data = wf.readframes(CHUNK)
while data != '':
    stream.write(data)
    data = wf.readframes(CHUNK)
stream.stop_stream()
stream.close()
p.terminate()


Record


"""PyAudio example: Record a few seconds of audio and save to a WAVE file."""
import pyaudio
import wave
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=RATE,
                input=True,
                frames_per_buffer=CHUNK)
print("* recording")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)
print("* done recording")
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()

三、关于声音录制的应用

之前有在python上做聊天室以及通讯功能的实例,其中利用到pyaudio进行声音的录制,对代码进行了简单修改。为了便于存储及识别,采用了将文件名命名为时间的形式,同时利用了全局变量JUDGE进行录制结束的判断。代码中的NOW与FILENAME用于存储录制时间及录制文件名,便于引用。本实例的最长录制时间为30s,使用时可根据个人需求更改TIME的值以达到修改最长录制时间的目的。使用时,先调用recorder中的函数record_wave,然后在录制结束时将recorder中的全局变量JUDGE置为False,即可完成录制。
以下为recorder.py的源代码:
   
#!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
#the longest record time
TIME = 30

FILENAME = ''
NOW = ''
SAVE = ''
JUDGE = True

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
  global JUDGE
  while JUDGE and count     #read NUM_SAMPLES sampling data
    string_audio_data = stream.read(NUM_SAMPLES)
    save_buffer.append(string_audio_data)
    count += 1
    print "."

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


本文为博主用做学习记录之需,即兴而写,供大家学习参考,若有代码排版等错误,敬请谅解。
pyaudio相关API文档地址 :  http://people.csail.mit.edu/hubert/pyaudio/docs/#class-pyaudio 

你可能感兴趣的:(python)