本文整理汇总了Python中pyaudio.PyAudio.open方法的典型用法代码示例。如果您正苦于以下问题:Python PyAudio.open方法的具体用法?Python PyAudio.open怎么用?Python PyAudio.open使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyaudio.PyAudio
的用法示例。
在下文中一共展示了PyAudio.open方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: record
# 需要导入模块: from pyaudio import PyAudio [as 别名]
# 或者: from pyaudio.PyAudio import open [as 别名]
def record():
pa = PyAudio()
in_stream = pa.open(format=paInt16, channels=1, rate=SAMPLING_RATE, input=True, frames_per_buffer=NUM_SAMPLES)
out_stream = pa.open(format=paInt16, channels=1, rate=SAMPLING_RATE,output=True)
save_count = 0
save_buffer = []
save_data = []
save_count = SAVE_LENGTH
while save_count>0:
string_audio_data = in_stream.read(NUM_SAMPLES)
audio_data = np.fromstring(string_audio_data, dtype=np.short)
save_buffer.append( string_audio_data )
save_data.append( audio_data )
save_count = save_count - 1
print 'save to test.wav'
save_wave_file("test.wav",save_buffer)
示例2: record
# 需要导入模块: from pyaudio import PyAudio [as 别名]
# 或者: from pyaudio.PyAudio import open [as 别名]
def record(self, time):
audio = PyAudio()
stream = audio.open(input_device_index=self.device_index,
output_device_index=self.device_index,
format=self.format,
channels=self.channel,
rate=self.rate,
input=True,
frames_per_buffer=self.chunk
)
print "Recording..."
frames = []
for i in range(0, self.rate / self.chunk * time):
data = stream.read(self.chunk)
frames.append(data)
stream.stop_stream()
print "Recording Complete"
stream.close()
audio.terminate()
write_frames = open_audio(self.file, 'wb')
write_frames.setnchannels(self.channel)
write_frames.setsampwidth(audio.get_sample_size(self.format))
write_frames.setframerate(self.rate)
write_frames.writeframes(''.join(frames))
write_frames.close()
self.convert()
示例3: sine_tone
# 需要导入模块: from pyaudio import PyAudio [as 别名]
# 或者: from pyaudio.PyAudio import open [as 别名]
def sine_tone(frequencies, amplitudes, duration, volume=1.0, sample_rate=22050):
n_samples = int(sample_rate * duration)
restframes = n_samples % sample_rate
p = PyAudio()
stream = p.open(format=p.get_format_from_width(1), # 8bit
channels=1, # mono
rate=sample_rate,
output=True)
def s(t):
r = 0
for i in range(0, len(frequencies)):
r += volume * amplitudes[i] * math.sin(2 * math.pi * frequencies[i] * t / sample_rate)
return r
samples = (int(s(t) * 0x7f + 0x80) for t in range(n_samples))
for buf in zip(*[samples]*sample_rate): # write several samples at a time
stream.write(bytes(bytearray(buf)))
# fill remainder of frameset with silence
stream.write(b'\x80' * restframes)
stream.stop_stream()
stream.close()
p.terminate()
示例4: MsgSender
# 需要导入模块: from pyaudio import PyAudio [as 别名]
# 或者: from pyaudio.PyAudio import open [as 别名]
class MsgSender():
"""
Designed for receive data stream.
"""
def __init__(self, RecorderConfig):
self.config = RecorderConfig
self.pPyAudioObj = PyAudio()
self.pStream = None
def handle(self):
self.pStream = self.pPyAudioObj.open(
format=self.config['format'],
channels=self.config['channels'],
rate=self.config['rate'],
frames_per_buffer=self.config['frames_per_buffer'],
input=True)
pStream = self.pStream
while True:
try:
data = pStream.read(self.config['bufferSize'])
except Exception, e:
print 'Cannot recognize read sound stream.\
Please check Network.client.MsgSender 1.'
print e
# lock g_dUserDict
if Defines.verify.g_pLock.acquire():
UserDict = deepcopy(Defines.verify.g_dUserDict)
Defines.verify.g_pLock.release()
# print 'UserDict: %s' % str(UserDict)
threading.Thread(
target=send2GroupThreaded,
args=(UserDict, data)
).start()
示例5: Audio_play
# 需要导入模块: from pyaudio import PyAudio [as 别名]
# 或者: from pyaudio.PyAudio import open [as 别名]
def Audio_play(filepath):
'''
play audio
'''
CHUNK = 1024
wf = wave.open(filepath, 'rb')
pa = PyAudio()
default_output = pa.get_default_host_api_info().get('defaultOutputDevice')
stream =pa.open(format = pa.get_format_from_width(wf.getsampwidth()),
channels = wf.getnchannels(),
rate = wf.getframerate(),
output = True,
output_device_index = default_output)
NUM = int(wf.getframerate()/CHUNK * 15)
logging.info(">> START TO PLAY AUDIO")
while NUM:
data = wf.readframes(CHUNK)
if data == " ": break
stream.write(data)
NUM -= 1
stream.stop_stream()
stream.close()
del data
pa.terminate()
示例6: sine_tone
# 需要导入模块: from pyaudio import PyAudio [as 别名]
# 或者: from pyaudio.PyAudio import open [as 别名]
def sine_tone(frequency, duration, volume=1, sample_rate=22050):
n_samples = int(sample_rate * duration)
restframes = n_samples % sample_rate
p = PyAudio()
stream = p.open(format=p.get_format_from_width(2), # 16 bit
channels=2,
rate=sample_rate,
output=True)
for i in xrange(0, 10):
if i % 2 == 0:
frequency = ZERO_FREQUENCY
else:
frequency = ONE_FREQUENCY
s = lambda t: volume * math.sin(2 * math.pi * frequency * t / sample_rate)
samples = (int(s(t) * 0x7f + 0x80) for t in xrange(n_samples))
for buf in izip(*[samples]*sample_rate): # write several samples at a time
stream.write(bytes(bytearray(buf)))
# fill remainder of frameset with silence
stream.write(b'\x80' * restframes)
stream.stop_stream()
stream.close()
p.terminate()
示例7: __init__
# 需要导入模块: from pyaudio import PyAudio [as 别名]
# 或者: from pyaudio.PyAudio import open [as 别名]
def __init__(self):
super(VCGame, self).__init__(255, 255, 255, 255, 800, 600)
# 初始化参数
# frames_per_buffer
self.numSamples = 1000
# 声控条
self.vbar = Sprite('black.png')
self.vbar.position = 20, 450
self.vbar.scale_y = 0.1
self.vbar.image_anchor = 0, 0
self.add(self.vbar)
# 皮卡丘类
self.pikachu = Pikachu()
self.add(self.pikachu)
# cocosnode精灵类
self.floor = cocos.cocosnode.CocosNode()
self.add(self.floor)
position = 0, 100
for i in range(120):
b = Block(position)
self.floor.add(b)
position = b.x + b.width, b.height
# 声音输入
audio = PyAudio()
SampleRate = int(audio.get_device_info_by_index(0)['defaultSampleRate'])
self.stream = audio.open(format=paInt16,
channels=1,
rate=SampleRate,
input=True,
frames_per_buffer=self.numSamples)
self.schedule(self.update)
示例8: play
# 需要导入模块: from pyaudio import PyAudio [as 别名]
# 或者: from pyaudio.PyAudio import open [as 别名]
def play():
wavName = 'test.wav'
print "play %s" % (wavName)
wf = wave.open(wavName, 'rb')
pa = PyAudio()
stream = pa.open(format=pa.get_format_from_width(wf.getsampwidth()),
channels=wf.getnchannels(),
rate=wf.getframerate(),
output=True)
data = wf.readframes(CHUNK)
td = threading.Thread(target=startGame)
td.start()
while data != '':
stream.write(data)
data = wf.readframes(CHUNK)
audio_data = np.fromstring(data, dtype=np.short)
print data
stream.stop_stream()
stream.close()
pa.terminate()
示例9: record
# 需要导入模块: from pyaudio import PyAudio [as 别名]
# 或者: from pyaudio.PyAudio import open [as 别名]
def record(self):
pa = PyAudio()
in_stream = pa.open(format=paInt16, channels=1, rate=SAMPLING_RATE, input=True, frames_per_buffer=BUFFER_SIZE)
save_count = 0
save_buffer = []
save_count = SAVE_LENGTH
print 'start recording'
while save_count>0:
string_audio_data = in_stream.read(BUFFER_SIZE)
audio_data = np.fromstring(string_audio_data, dtype=np.short)
save_buffer.append( string_audio_data )
save_count = save_count - 1
print 'save %s' % (self.fileName)
pa.terminate()
wf = wave.open(self.fileName, 'wb')
wf.setnchannels(1)
wf.setsampwidth(2)
wf.setframerate(SAMPLING_RATE)
wf.writeframes("".join(save_buffer))
wf.close()
self.stringAudioData = "".join(save_buffer)
save_data = np.fromstring(self.stringAudioData, dtype=np.short)
self.audioData = save_data[10000:10000+4608*4]
self.stringAudioData = self.audioData.tostring()
self.cutAudio = self.audioData
# self.cut2()
self.getFeature()
示例10: rec_audio
# 需要导入模块: from pyaudio import PyAudio [as 别名]
# 或者: from pyaudio.PyAudio import open [as 别名]
def rec_audio(stat,filename,queue):
NUM_SAMPLES = 200
SAMPLING_RATE = 8000
pa = PyAudio()
stream = pa.open(format=paInt16, channels=1, rate=SAMPLING_RATE, input=True, frames_per_buffer=NUM_SAMPLES)
save_count = 0
save_buffer = []
while True:
signal=queue.get()
if(signal=="audio_start"):
break
time_start=clock()
while True:
string_audio_data = stream.read(NUM_SAMPLES)
save_buffer.append( string_audio_data )
if(stat.value==1):
break
time_finish=clock()
wf = wave.open("./temp_frame/"+filename+".wav", 'wb')
wf.setnchannels(1)
wf.setsampwidth(2)
wf.setframerate(SAMPLING_RATE)
wf.writeframes("".join(save_buffer))
wf.close()
save_buffer = []
print("audio_start: "+str(time_start))
print("audio_end: "+str(time_finish))
print("audio_duration (sec): "+str(time_finish-time_start)) #duration (second)
print ("audio_file: ", filename, "saved" )
queue.put("wav_sav_ok")
示例11: __init__
# 需要导入模块: from pyaudio import PyAudio [as 别名]
# 或者: from pyaudio.PyAudio import open [as 别名]
def __init__(self):
self.THRESHOLD = 200
self.CHUNK_SIZE = 1024
self.RATE = 22100
p = PyAudio()
self.stream = p.open(format=paInt16, channels=1, rate=self.RATE, input=True, output=True, frames_per_buffer=self.CHUNK_SIZE)
示例12: record
# 需要导入模块: from pyaudio import PyAudio [as 别名]
# 或者: from pyaudio.PyAudio import open [as 别名]
def record(self):
#open the input of wave
pa = PyAudio()
stream = pa.open(format = paInt16, channels = 1,
rate = self.getRate(pa), input = True,
frames_per_buffer = self.NUM_SAMPLES)
save_buffer = []
record_start = False
record_end = False
no_record_times = 0
while 1:
#read NUM_SAMPLES sampling data
string_audio_data = stream.read(self.NUM_SAMPLES)
if record_start == True :save_buffer.append(string_audio_data)
print max(array('h', string_audio_data))
if max(array('h', string_audio_data)) >5000:
record_start = True
no_record_times = 0
else:
no_record_times += 1
if record_start == False:continue
if no_record_times >10:
break
stream.close()
pa.terminate()
return save_buffer
示例13: __init__
# 需要导入模块: from pyaudio import PyAudio [as 别名]
# 或者: from pyaudio.PyAudio import open [as 别名]
class pybeeptone:
def __init__(self, rate=44100):
self.rate = 44100
self.pyaudio = PyAudio()
self.stream = self.pyaudio.open(
format = self.pyaudio.get_format_from_width(1),
channels = 1, rate = self.rate, output = True)
def play_tone(self, freq=1000, duration=0.3):
rate = self.rate
length = int(math.ceil(self.rate*duration))
data = ''.join( [chr(int(math.sin(x/((rate/freq)/math.pi))*127+128))
for x in xrange(length)] )
self.stream.write(data)
def play_rest(self, duration):
rate = self.rate
length = int(math.ceil(self.rate*duration))
data = ''.join( [chr(int(128)) for x in xrange(length)] )
self.stream.write(data)
def close(self):
self.stream.stop_stream()
self.stream.close()
self.pyaudio.terminate()
示例14: main
# 需要导入模块: from pyaudio import PyAudio [as 别名]
# 或者: from pyaudio.PyAudio import open [as 别名]
def main():
# read in some block data from pyaudio
RATE=44100
INPUT_BLOCK_TIME=0.2
INPUT_FRAMES_PER_BLOCK=int(RATE*INPUT_BLOCK_TIME)
pa=PyAudio()
data=True
fmt="%dh"%INPUT_FRAMES_PER_BLOCK
total_rms=0
total_blocks=0
while data:
for dr,subdr,fnames in os.walk(path):
for filename in fnames:
try:
print filename
wf=wave.open("%s/%s"%(path,filename),'rb')
strm=pa.open(format=pa.get_format_from_width(wf.getsampwidth()),
channels=wf.getnchannels(),
rate=wf.getframerate(),
input=True)
strm.stop_stream()
strm.close()
d=wf.readframes(INPUT_FRAMES_PER_BLOCK)
d=struct.unpack(fmt,d)
wf.close()
total_rms+=calc_rms(d)
total_blocks+=1
except:
#print e
print "*** ERROR ***"
data=False
avg=total_rms/total_blocks
print "The average is %f"%avg
示例15: Stream
# 需要导入模块: from pyaudio import PyAudio [as 别名]
# 或者: from pyaudio.PyAudio import open [as 别名]
class Stream(Thread):
def __init__(self, f, on_terminated):
self.__active = True
self.__path = f
self.__paused = True
self.on_terminated = on_terminated
self.__position = 0
self.__chunks = []
self.__pyaudio = PyAudio()
Thread.__init__(self)
self.start()
def play(self):
self.__paused = False
def seek(self, seconds):
self.__position = int(seconds * 10)
def is_playing(self):
return self.__active and not self.__paused
def get_position(self):
return int(self.__position / 10)
def get_duration(self):
return int(len(self.__chunks) / 10)
def pause(self):
self.__paused = True
def kill(self):
self.__active = False
def __get_stream(self):
self.__segment = AudioSegment.from_file(self.__path)
self.__chunks = make_chunks(self.__segment, 100)
return self.__pyaudio.open(format=self.__pyaudio.get_format_from_width(self.__segment.sample_width),
channels=self.__segment.channels,
rate=self.__segment.frame_rate,
output=True)
def run(self):
stream = self.__get_stream()
while self.__position < len(self.__chunks):
if not self.__active:
break
if not self.__paused:
# noinspection PyProtectedMember
data = self.__chunks[self.__position]._data
self.__position += 1
else:
free = stream.get_write_available()
data = chr(0) * free
stream.write(data)
stream.stop_stream()
self.__pyaudio.terminate()
if self.__active:
self.on_terminated()