当前位置: 首页>>代码示例>>Python>>正文


Python pyaudio.PyAudio类代码示例

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


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


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