• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python pyaudio.PyAudio类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pyaudio.PyAudio的典型用法代码示例。如果您正苦于以下问题:Python PyAudio类的具体用法?Python PyAudio怎么用?Python PyAudio使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了PyAudio类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: __init__

	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)
开发者ID:ricsirke,项目名称:SoundFreqPlotter,代码行数:7,代码来源:audio.py


示例2: rec_audio

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")
开发者ID:pentium3,项目名称:cam,代码行数:35,代码来源:cam_recorder.py


示例3: __init__

	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)
开发者ID:Guaderxx,项目名称:Games,代码行数:31,代码来源:Game2.py


示例4: record

def record():

	pa = PyAudio()
	in_stream = pa.open(format=paInt16, channels=1, rate=SAMPLING_RATE, input=True, frames_per_buffer=BUFFER_SIZE)
	out_stream = pa.open(format=paInt16, channels=1, rate=SAMPLING_RATE,output=True)
	save_count = 0
	save_buffer = []
	save_data   = []

	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)
		
		print type(audio_data)
		save_buffer.append( string_audio_data )
		save_data.append( audio_data )

		save_count = save_count - 1

#print 'save %s' % (wav.fileName)
#save_wave_file(wav.fileName, save_buffer)
		save_wave_file("test.wav", save_buffer)
		pa.terminate()
开发者ID:ej0cl6,项目名称:ciao,代码行数:27,代码来源:tool1.py


示例5: record

	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()
开发者ID:ej0cl6,项目名称:ciao,代码行数:32,代码来源:Wav.py


示例6: sine_tone

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()
开发者ID:yhamoudi,项目名称:Shape-Indexing,代码行数:26,代码来源:sound.py


示例7: __init__

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()
开发者ID:argon2008-aiti,项目名称:pybeeptone,代码行数:25,代码来源:pybeeptone.py


示例8: record

    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
开发者ID:cyb880326,项目名称:pySmartHome,代码行数:31,代码来源:microphone.py


示例9: main

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
开发者ID:sittigboyd,项目名称:dragonbot-listen,代码行数:34,代码来源:calc_avg_rms.py


示例10: sine_tone

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()
开发者ID:kku1993,项目名称:sound-chat,代码行数:27,代码来源:play.py


示例11: play

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()
开发者ID:ej0cl6,项目名称:ciao,代码行数:27,代码来源:tool3.py


示例12: record

 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()
开发者ID:AnanthaRajuC,项目名称:homecontrol,代码行数:26,代码来源:pygsr.py


示例13: Stream

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()
开发者ID:mRokita,项目名称:sMusic-core,代码行数:59,代码来源:player.py


示例14: worker

 def worker():
     p = PyAudio()
     stream = p.open(format=p.get_format_from_width(2),
                     channels=1, rate=44100, output=True)
     while True:
         self.lock.acquire()
         stream.write(self.wavdata.tostring())
         self.lock.release()
开发者ID:chriskuech,项目名称:wavelab,代码行数:8,代码来源:composer.py


示例15: Audio_record_play

def Audio_record_play(seconds,play,filename):
    '''
    This function include record and play, if you want to play and record,
    please set the play is True.
    The sample rate is 44100
    Bit:16
    '''
    CHUNK = 1024
    CHANNELS = 2
    SAMPLING_RATE = 44100
    FORMAT = paInt16
    NUM = int(SAMPLING_RATE/CHUNK * seconds)

    save_buffer = []

    if play is True:
        source_file = autohandle_directory + '/audio_lib/'+'source1.wav'
        swf = wave.open(source_file, 'rb')
    
    #open audio stream
    pa = PyAudio()
    default_input = pa.get_default_host_api_info().get('defaultInputDevice')
    stream = pa.open(
                    format   = FORMAT, 
                    channels = CHANNELS, 
                    rate     = SAMPLING_RATE, 
                    input    = True,
                    output   = play,
                    frames_per_buffer  = CHUNK,
                    input_device_index = default_input
                    )

    logging.info(">> START TO RECORD AUDIO")
    while NUM:
        save_buffer.append(stream.read(CHUNK))
        NUM -= 1
        if play is True:
            data = swf.readframes(CHUNK)
            stream.write(data)
            if data == " ": break

    #close stream
    stream.stop_stream()
    stream.close()
    pa.terminate()

    # save wav file
    def save_wave_file(filename,data):
        wf_save = wave.open(filename, 'wb')
        wf_save.setnchannels(CHANNELS)
        wf_save.setsampwidth(pa.get_sample_size(FORMAT))
        wf_save.setframerate(SAMPLING_RATE)
        wf_save.writeframes("".join(data))
        wf_save.close()

    save_wave_file(filename, save_buffer)

    del save_buffer[:]
开发者ID:hakehuang,项目名称:Auana-P,代码行数:58,代码来源:autool.py


示例16: __init__

class RadioServer:
	def __init__(self):
		self.pa=PyAudio()
		self.input_names={}
		self.output_names={}
		self.listeners=[]

	def registerDevices(self,inputDevice=None,outputDevice=None):
		if inputDevice==None:
			self.inputDevice=InputDevice(self.pa)
		else:
			self.inputDevice=inputDevice

		if outputDevice==None:
			self.outputDevice=OutputDevice(self.pa)
		else:
			self.outputDevice=outputDevice



	def registerInput(self,descriptor,name):
		self.input_names[name]=descriptor

	def registerOutput(self,descriptor,name):
		self.output_names[name]=descriptor

	def subscribeToInput(self,name,queue):
		self.inputDevice.subscribe(queue,self.input_names[name])

	def subscribeToOutput(self,name,queue):
		self.outputDevice.subscribe(queue,self.output_names[name])

	def addListener(self,listener):
		self.listeners.append(listener)
		listener.bind(self)

	def start(self):
		for l in self.listeners:
			l.start()
		self.inputDevice.start()
		self.outputDevice.start()

	def stop(self):
		self.inputDevice.stop()
		self.outputDevice.stop()
		for l in self.listeners:
			l.stop()
		self.pa.terminate()

	def sigint(self,signal,frame):
		self.stop()

	def run_forever(self):
		self.start()
		signal.signal(signal.SIGINT,lambda s,f:self.sigint(s,f))
		signal.pause()
开发者ID:gdkar,项目名称:RadioServer,代码行数:56,代码来源:RadioServer.py


示例17: playWaveData

 def playWaveData(self, waveData):
     p = PyAudio()
     stream = p.open(format = p.get_format_from_width(1),
                     channels = 1,
                     rate = self.bitRate,
                     output = True)
     stream.write(waveData)
     stream.stop_stream()
     stream.close()
     p.terminate()
开发者ID:jrhoeber,项目名称:terminalComposer,代码行数:10,代码来源:PitchGenerator.py


示例18: record_wave

    def record_wave(self):
        #open the input of wave 
        pa = PyAudio() 
        stream = pa.open(format = paInt16, channels = 1, 
        rate = self.framerate, input = True, 
        frames_per_buffer = self.NUM_SAMPLES) 
        save_buffer = [] 
        count = 0 
        while count < self.TIME*5:
            string_audio_data = stream.read(self.NUM_SAMPLES)
            audio_data = np.fromstring(string_audio_data, dtype=np.short)
            # 得到audio_data中大约level的数据个数
            large_sample_count = np.sum( audio_data > self.LEVEL )
            #print large_sample_count
            #print 'mute_begin' + str(self.mute_begin)
            #print 'mute_end' + str(self.mute_end)
            #未开始计时,出现静音
            # 如果一帧数据数据的有效数据小于mute_count_limit,则认为是静音
            if large_sample_count < self.mute_count_limit :
                # 初始化静音计数
                self.mute_begin=1
            else:
                # 如果有声音出现
                save_buffer.append(string_audio_data)  
                # 静音标记为否
                self.mute_begin=0
                # 静音时长为0
                self.mute_end=1
            count += 1
            # 如果静音时长大于5
            if (self.mute_end - self.mute_begin) > 3:
                # 还原变量
                self.mute_begin=0
                # 还原变量
                self.mute_end=1
                # 结束本次从声卡取值,本次录音结束
                break
            # 如果是静音,那么自增静音时长mute_end
            if self.mute_begin:
                self.mute_end+=1  
        
        save_buffer=save_buffer[:]
        if save_buffer:
            if self.file_name_index < 11:
                pass
            else:
                self.file_name_index = 1
            filename = str(self.file_name_index)+'.wav' 
            self.save_wave_file(filename=filename, data=save_buffer)
            self.writeQ(queue=self.wav_queue, data=filename)
            self.file_name_index+=1

        save_buffer = []
        #在嵌入式设备上必须加这一句,否则只能录音一次,下次录音时提示stram overflow 错误。
        stream.close()
开发者ID:zhangzhenfeng,项目名称:marginer,代码行数:55,代码来源:recorder.py


示例19: Record

    def Record(self):
        global CHANNELS

        # 开启声音输入
        pa = PyAudio()
        stream = pa.open(format=paInt16, channels=CHANNELS, rate=self.sampling_rate, input=True, 
                        frames_per_buffer=self.cacheblock_size)

        save_count = 0          # 已经保存的样本块
        silence_count = 0       # 持续无声音的样本块
        save_buffer = []        # 音频缓冲

        try:
            print "start recording"
            while True:
                # 录音、取样
                string_audio_data = stream.read(self.cacheblock_size)
                # 将读入的数据转换为数组
                audio_data = np.fromstring(string_audio_data, dtype=np.short)
                # 样本值大于LEVEL的取样为成功取样,计算成功取样的样本的个数
                large_sample_count = np.sum(audio_data > self.level)
                print "Peak:",np.max(audio_data),"    Sum:",large_sample_count
                # 如果成功取样数大于SAMPLING_NUM,则当前数据块取样都成功
                if large_sample_count > self.sampling_num:
                    # 有成功取样的数据块时,样本计数+1
                    save_count += 1
                else:
                    # 有成功录取的块后,若取样失败,此时可能处于静音状态,静音计数+1
                    if(save_count > 0):
                        silence_count += 1

                # 取样失败次数是否超过最大值
                if (save_count <= self.max_save_length) and (silence_count <= self.max_silence_length):
                    # 将要保存的数据存放到save_buffer中
                    save_buffer.append(string_audio_data)
                else:
                    # 将save_buffer中的数据写入WAV文件,WAV文件的文件名是保存的时刻
                    if len(save_buffer) > 0:
                        self.filename = datetime.now().strftime("%Y-%m-%d_%H_%M_%S") + ".wav"
                        self.__Save_wave_file(self.filename, save_buffer)
                        save_buffer = []
                        print self.filename, "saved"
                    break
        except KeyboardInterrupt:
            print "manual exit"
        finally:
            # stop stream
            stream.stop_stream()  
            stream.close()
            # close PyAudio  
            pa.terminate() 
            print "exit recording"

        return self.filename
开发者ID:GloryChou,项目名称:Robotics-N,代码行数:54,代码来源:rnaudio.py


示例20: play

	def play(self):
		print "play %s" % (self.fileName)
		pa = PyAudio()
		stream = pa.open(format=paInt16, channels=1, rate=SAMPLING_RATE, output=True, frames_per_buffer=BUFFER_SIZE)
		
		stream.write(self.stringAudioData)
		# stream.write(self.cutAudio)
		
		stream.stop_stream()
		stream.close()
		pa.terminate()
开发者ID:ej0cl6,项目名称:ciao,代码行数:11,代码来源:Wav.py



注:本文中的pyaudio.PyAudio类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python pyautogui.click函数代码示例发布时间:2022-05-25
下一篇:
Python pyaudio.get_sample_size函数代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap