def _processAudioFrame(self, d): # Decode audio frame afr = self.ac.decode(d[1]) if afr: # See if we have to set up the sound if self.snd == None: self.aBitRate = afr.bitrate self.aSampleRate = afr.sample_rate self.aChannels = afr.channels try: # Hardcoded S16 ( 16 bit signed ) for now #print 'Opening sound', afr.sample_rate, afr.channels, sound.AFMT_S16_LE, self.audioCard self.snd = sound.Output(afr.sample_rate, afr.channels, sound.AFMT_S16_LE, self.audioCard) self.resampler = None except: try: # Create a resampler when no multichannel sound is available self.resampler = sound.Resampler( (afr.sample_rate, afr.channels), (afr.sample_rate, 2)) # Fallback to 2 channels #print 'Falling back to', afr.sample_rate, 2, sound.AFMT_S16_LE, self.audioCard self.snd = sound.Output(afr.sample_rate, 2, sound.AFMT_S16_LE, self.audioCard) except: self.err.append(sys.exc_info()) raise # Calc max buf size for better audio handling if self.maxBufSize == -1: self.maxBufSize = self.snd.getSpace() # Handle the PTS accordingly snd = self.snd if d[3] > 0 and self.aDelta == 0 and snd: # set correction factor in case of PTS presence self.aDelta = (float(d[3]) / 90000) - snd.getPosition() - snd.getLeft() # Play the raw data if we have it if len(afr.data) > 0: # Split the audio data if the size of data chunk larger than the buffer size data = afr.data if len(data) > self.maxBufSize: data = str(data) while len(data) > self.maxBufSize: chunk = data[:self.maxBufSize] data = data[self.maxBufSize:] self.aDecodedFrames.append( (chunk, afr.sample_rate, afr.channels)) self.aDecodedFrames.append( (data, afr.sample_rate, afr.channels)) self._processAudio()
def processAudioFrame(self, d): # Decode audio frame afr = self.ac.decode(d[1]) if afr: # See if we set up the sound if self.snd == None: self.aBitRate = afr.bitrate #print 'Sound: ', afr.sample_rate, afr.channels, afr.bitrate try: # Hardcoded S16 ( 16 bit signed ) for now self.snd = sound.Output(afr.sample_rate, afr.channels, sound.AFMT_S16_LE) self.resampler = None except: try: # Create a resampler when no multichannel sound is available self.resampler = sound.Resampler( (afr.sample_rate, afr.channels), (afr.sample_rate, 2)) # Fallback to 2 channels self.snd = sound.Output(afr.sample_rate, 2, sound.AFMT_S16_LE) except: traceback.print_exc() self.err.append(sys.exc_info()[1]) return # See if we need to resample the audio data s = afr.data if self.resampler: s = self.resampler.resample(s) # Handle the PTS accordingly if d[3] > 0 and self.aDelta == 0: # set correction factor in case of PTS presence self.aDelta = (float(d[3]) / 90000 ) - self.snd.getPosition() - self.snd.getLeft() # Play the raw data if we have it if len(s) > 0: self.aDecodedFrames.append(s) while len(self.aDecodedFrames): # See if we can play sound chunk without clashing with the video frame if len(s) > self.snd.getSpace(): break #print 'LEFT:', self.snd.getLeft(), len( s ), self.snd.getSpace() self.snd.play(self.aDecodedFrames.pop(0))
def wav(filename): """ WAV file format reader/player """ import wave, pymedia.audio.sound as sound with wave.open(filename, 'rb') as f: snd = sound.Output(f.getframerate(), f.getnchannels(), sound.AFMT_S16_LE) snd.play(f.readframes())
def play(file_path): #file_path = "test.mp3" root, ext = path.splitext(file_path) demuxer = muxer.Demuxer(ext[1:].lower()) decoder = None output = None file = open(file_path, 'rb') data = ' ' while data: data = file.read(90000) if len(data): frames = demuxer.parse(data) for frame in frames: if decoder == None: decoder = acodec.Decoder(demuxer.streams[0]) audio_frame = decoder.decode(frame[1]) if audio_frame and audio_frame.data: if output == None: output = sound.Output(audio_frame.sample_rate, audio_frame.channels, sound.AFMT_S16_LE) #while self.stop: #time.sleep(1) output.play(audio_frame.data) while output.isPlaying(): time.sleep(0.05)
def run(self): client = maryclient() client.set_locale("fr") client.set_voice("upmc-pierre") #print('generation du son') the_sound = client.generate( self._text) #"Bonjour je m'appelle clément") #print('lecture du son') buf = StringIO.StringIO(the_sound) f = wave.open(buf, 'rb') sampleRate = f.getframerate() channels = f.getnchannels() format = sound.AFMT_S16_LE snd = sound.Output(sampleRate, channels, format) s = f.readframes(300000) snd.play(s) while snd.isPlaying(): time.sleep(0.05)
def playAudio(filename): import pymedia.audio.acodec as acodec import pymedia.muxer as muxer import pymedia.audio.sound as sound import time name1 = str.split(filename, '.') # Open demuxer first dm = muxer.Demuxer(name1[-1].lower()) dec = None snd = None s = " " f = open(filename, 'rb') while len(s): s = f.read(20000) if len(s): # 解析出最初的几帧音频数据 frames = dm.parse(s) for fr in frames: if dec == None: # Open decoder dec = acodec.Decoder(dm.streams[0]) #音频数据在 frame 数组的第二个元素中 r = dec.decode(fr[1]) if r and r.data: if snd == None: snd = sound.Output(r.sample_rate, r.channels, sound.AFMT_S16_LE) snd.play(r.data) #8.延时,直到播放完毕 while snd.isPlaying(): time.sleep(0.5)
def run(self): dm = muxer.Demuxer(str.split(self.mfile, '.')[-1].lower()) self.snd = dec = None s = self.getbuff() while len(s) and not self.stop: frames = dm.parse(s) if frames: for fr in frames: if dec == None: dec = acodec.Decoder(dm.streams[fr[0]]) r = dec.decode(fr[1]) if r and r.data: if self.snd == None: self.snd = sound.Output(int(r.sample_rate), r.channels, sound.AFMT_S16_LE) data = r.data self.snd.play(data) s = self.getbuff() # 淡出 fade_out(self.snd) # 停止 self.snd.stop() # 设置音量正常 self.snd.setVolume(65535)
def loadSounds(self): ''' Load sound files from preferences ''' try: import wave import pymedia.audio.sound as sound SoundManager.HAS_PYMEDIA = True except ImportError: SoundManager.HAS_PYMEDIA = False try: import pygame.mixer from pygame.mixer import Sound pygame.mixer.init() except ImportError: import sys sys.stderr.write( 'Pymedia and pygame are not available, one of which is needed for sound support.' ) sys.exit(1) self.sounds = {} o = OptionManager() r = ResourceManager() for s in constants.SOUNDS: opt = o.get_default_option( s, r["resources"]["sounds"][constants.DEFAULT_SOUND]) if SoundManager.HAS_PYMEDIA: f = wave.open(opt, 'rb') if f.getsampwidth() > 1: snd = sound.Output(f.getframerate(), f.getnchannels(), sound.AFMT_S16_LE) else: snd = sound.Output(f.getframerate(), f.getnchannels(), sound.AFMT_U8) self.sounds[s] = { "frames": f.readframes(self.max_ms), "snd": snd } f.close() else: self.sounds[s] = Sound(opt)
def play(self): self.stopFlag = True self.mp3 = [] self.i = 0 #dm = muxer.Demuxer(str.split(self.file_name, '.')[-1].lower()) dm = muxer.Demuxer('mp3') #f = open(self.file_name, 'rb') snd = dec = None header = { #'Referer': 'http://www.xiami.com/', 'User-Agent': 'User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36', } request = urllib2.Request(self.file_name, headers=header) self.f = urllib2.urlopen(request) print 'Player Init Time:%s' % (time.time() - TIME) #s = self.f.read(32000) s = self.f.read(10000) #thread.start_new_thread(self.download,()) self.tcpFlag = True #self.TcpThread = tcpThread(self) #self.TcpThread.start() #self.downloadthread = downloadThread(self.f, self.mp3) #self.downloadthread.start() while self.stopFlag: pass print 'first read long:%s' % (len(s)) while len(s) and self.tcpFlag: frames = dm.parse(s) if frames: for fr in frames: if dec == None: dec = acodec.Decoder(dm.streams[fr[0]]) r = dec.decode(fr[1]) if r and r.data: if snd == None: snd = sound.Output(int(r.sample_rate), r.channels, sound.AFMT_S16_LE) data = r.data try: snd.play(data) except Exception, e: print e #sys.exit(0) ''' if self.i<len(self.mp3): s = self.mp3[self.i] else: s = [] self.i = self.i + 1 ''' s = self.f.read(2000)
def aplayer(name, card, rate, tt): import pymedia.muxer as muxer, pymedia.audio.acodec as acodec, pymedia.audio.sound as sound import time dm = muxer.Demuxer(str.split(name, '.')[-1].lower()) snds = sound.getODevices() if card not in range(len(snds)): raise 'Cannot play sound to non existent device %d out of %d' % ( card + 1, len(snds)) f = open(name, 'rb') snd = resampler = dec = None s = f.read(32000) t = 0 while len(s): frames = dm.parse(s) if frames: for fr in frames: # Assume for now only audio streams if dec == None: print dm.getInfo(), dm.streams dec = acodec.Decoder(dm.streams[fr[0]]) r = dec.decode(fr[1]) if r and r.data: if snd == None: print 'Opening sound with %d channels -> %s' % ( r.channels, snds[card]['name']) snd = sound.Output(int(r.sample_rate * rate), r.channels, sound.AFMT_S16_LE, card) if rate < 1 or rate > 1: resampler = sound.Resampler( (r.sample_rate, r.channels), (int(r.sample_rate / rate), r.channels)) print 'Sound resampling %d->%d' % ( r.sample_rate, r.sample_rate / rate) data = r.data if resampler: data = resampler.resample(data) if EMULATE: # Calc delay we should wait to emulate snd.play() d = len(data) / float(r.sample_rate * r.channels * 2) time.sleep(d) if int(t + d) != int(t): print 'playing: %d sec\r' % (t + d), t += d else: snd.play(data) if tt > 0: if snd and snd.getPosition() > tt: break s = f.read(512) while snd.isPlaying(): time.sleep(.05)
def set_bgm(plugin_vals): snd = sound.Output(5, 1, sound.AFMT_S16_LE) # whatever def do(arg): if arg == 'on': fade_in(snd) elif arg == 'off': fade_out(snd) return do
def play_sound(self, sound_filename): try: self.s = wave.open(sound_filename, 'rb') sample_rate = self.s.getframerate() channels = self.s.getnchannels() frmt = sound.AFMT_S16_LE self.snd = sound.Output(sample_rate, channels, frmt) s = self.s.readframes(300000) self.snd.play(s) except: pass
def file_dialog(self): f = wave.open('phone-off-hook-1.wav', 'rb') sampleRate = f.getframerate() channels = f.getnchannels() format = sound.AFMT_S16_LE snd = sound.Output(sampleRate, channels, format) s = f.readframes(300000) snd.play(s) while snd.isPlaying(): time.sleep(0.05)
def playWAV(fname): import pymedia.audio.sound as sound import time, wave f = wave.open(fname, 'rb') sampleRate = f.getframerate() channels = f.getnchannels() format = sound.AFMT_S16_LE snd1 = sound.Output(sampleRate, channels, format) s = ' ' while len(s): s = f.readframes(1000) snd1.play(s)
def __init__(self, sample_rate=44100, channels=2, format="S16_LE"): super(RawSoundOutput, self).__init__() pformat = mapping_format_to_pymedia[format] self.snd = sound.Output(sample_rate, channels, pformat) self.chunksize = sample_rate / 40 # no idea why, but it seems we need to pass to pymedia chunks of a sufficiently short duration to prevent playback artefacts mask = 4 * channels - 1 # self.chunksize = self.chunksize - (self.chunksize & mask) # ensure whole number of samples from math import log # round to nearest power of 2 self.chunksize = 2**int(log(self.chunksize) / log(2))
def run(self): logging.info('play started on ' + self.filename) dm = muxer.Demuxer(str.split(self.filename, '.')[-1].lower()) snds = sound.getODevices() if 0 not in range(len(snds)): print 'Cannot play sound to non existent device %d out of %d' % ( 1, len(snds)) self.endfunc() return f = open(self.filename, 'rb') snd = resampler = dec = None s = f.read(32000) t = 0 while len(s): frames = dm.parse(s) if frames: for fr in frames: # Assume for now only audio streams if dec == None: print dm.getInfo(), dm.streams dec = acodec.Decoder(dm.streams[fr[0]]) r = dec.decode(fr[1]) if r and r.data: if snd == None: print 'Opening sound with %d channels -> %s' % ( r.channels, snds[0]['name']) snd = sound.Output(int(r.sample_rate), r.channels, sound.AFMT_S16_LE, 0) data = r.data while (self.state == PAUSE): time.sleep(.05) if (self.state == STOP): self.endfunc() return snd.play(data) s = f.read(BUFFER_SIZE) count = 0 while snd.isPlaying(): count = count + 1 print "playing: ", str(count) time.sleep(.05) while (self.state == PAUSE): time.sleep(.05) if (self.state == STOP): self.endfunc() return self.endfunc()
def playWAV(fname): f = wave.open(fname, 'rb') sampleRate = f.getframerate() channels = f.getnchannels() format = sound.AFMT_S16_LE snd1 = sound.Output(sampleRate, channels, format) s = ' ' while len(s): s = f.readframes(1000) snd1.play(s) # Since sound module is not synchronous we want everything to be played before we exit while snd1.isPlaying(): time.sleep(0.05)
def playPCM( fname, sampleRate ): import pymedia.audio.sound as sound import time snd1= sound.Output( sampleRate, 2, sound.AFMT_S16_LE ) f= open( fname, 'rb' ) s= ' ' while len( s ): s= f.read( 40960 ) snd1.play( s ) print 'Played %d bytes, pos %f ' % ( len( s ), snd1.getPosition() ) while snd1.isPlaying(): time.sleep( 0.05 )
def play_by_pymedia(sound_file): file_type = str.split( sound_file, '.' )[ -1 ].lower() #1.二进制方法读取前 10000 个字节,保证能读到第一帧音频数据 f = open( sound_file, 'rb' ) data= f.read(4096) #data= f.read() #2.创建合成器对象,解析出最初的几帧音频数据 import pymedia.muxer as muxer dm = muxer.Demuxer(file_type) frames = dm.parse( data ) #print len(frames) #3.根据解析出来的 Mp3 编码信息,创建解码器对象 import pymedia.audio.acodec as acodec #dec = acodec.Decoder( dm.streams[ 0 ] ) #像下面这样也行 params = {'id': acodec.getCodecID(file_type), 'bitrate': 128000, 'sample_rate': 44100, 'ext': 'mp3', 'channels': 2} dec= acodec.Decoder(params) if len(frames) > 1: #4.解码第一帧音频数据 frame = frames[0] #音频数据在 frame 数组的第二个元素中 r= dec.decode( frame[ 1 ] ) print "sample_rate:%s , channels:%s " % (r.sample_rate,r.channels) #注意:这一步可以直接解码 r=dec.decode( data),而不用读出第一帧音频数据 #但是开始会有一下噪音,如果是网络流纯音频数据,不包含标签信息,则不会出现杂音 else: r=dec.decode(data) #5.创建音频输出对象 import pymedia.audio.sound as sound snd = sound.Output( r.sample_rate, r.channels, sound.AFMT_S16_LE ) #6.播放 if r: snd.play_all(r.data) #7.继续读取、解码、播放 while True: data = f.read(512) if len(data)>0: r = dec.decode( data ) if r: snd.play_all(r.data) else: break #8.延时,直到播放完毕 import time while snd.isPlaying(): time.sleep( .5 )
def __init__(self, sample_rate=44100, channels=2, format="S16_LE", maximumLag=0.0): """x.__init__(...) initializes x; see x.__class__.__doc__ for signature""" super(Output, self).__init__() pformat = format2PyMediaFormat[format] self.snd = sound.Output(sample_rate, channels, pformat) self.chunksize = sample_rate / 40 # no idea why, but it seems we need to pass to pymedia chunks of a sufficiently short duration to prevent playback artefacts mask = 4 * channels - 1 # round to nearest power of 2 self.chunksize = 2**int(log(self.chunksize) / log(2)) self.maxLag = int(maximumLag * sample_rate * channels * format2BytesPerSample[format])
def openPlayer(self, wavfile): if pyaudiopresent: p = pyaudio.PyAudio() self.samplewidth = wavfile.getsampwidth() self.output = p.open(format=p.get_format_from_width( wavfile.getsampwidth()), channels=wavfile.getnchannels(), rate=wavfile.getframerate(), output=True) self.bytes_per_second = wavfile.getsampwidth( ) * wavfile.getframerate() * wavfile.getnchannels() self.sample_size = wavfile.getsampwidth() * wavfile.getnchannels() elif pymediapresent: if self.format < 0: self.format = sound.AFMT_S16_LE self.samplewidth = 2 # create an audio output device self.output = sound.Output(self.samplerate, self.channels, self.format)
def aplayer( name ): import pymedia.audio.acodec as acodec import pymedia.audio.sound as sound import pymedia.muxer as muxer import time dm= muxer.Demuxer( name.split( '.' )[ -1 ].lower() ) f= open( name, 'rb' ) s= f.read( 90000 ) frames= dm.parse( s ) dec= acodec.Decoder( dm.streams[ frames[ 0 ] [ 0 ] ] ) # dec= acodec.Decoder( str.split( name, '.' )[ -1 ].lower() ) br= None snd= None f.seek(0) s= f.read( 50000 ) while len( s ): r= dec.decode( s ) if snd== None: print 'Opening sound with %d channels( %d bitrate )' % ( r.channels, r.bitrate ) snd= sound.Output( r.sample_rate, r.channels, sound.AFMT_S16_LE ) br= r.bitrate if r: snd.play( r.data ) ev= pygame.event.get() s= f.read( 512 ) for e in ev: if e.type== pygame.KEYDOWN: if e.key== pygame.K_RIGHT: # Seek forward f.seek( SEEK_SEC* br/ 8, 1 ) dec.reset() if e.key== pygame.K_LEFT: # Seek forward if f.tell()> SEEK_SEC* br/ 8: f.seek( -SEEK_SEC* br/ 8, 1 ) dec.reset() if e.key== pygame.K_ESCAPE: s= '' break while snd.isPlaying(): time.sleep( .05 )
def playCash(self, temp): try: d = None dns = 'Provider=Microsoft.Jet.OLEDB.4.0;User ID=ikmdb;Data Source=%s;Persist Security Info=False;Jet OLEDB:System database=%s' % (self._insiderdb, self._sysdb) sql = 'SELECT TOP 1 iif ( IsNull(SCardType), "", SCardType ) AS SCardType, iif ( IsNull(InsiderMoney), "", InsiderMoney ) AS InsiderMoney FROM [InsiderInfo] WHERE InsiderNumber = "%s"' % temp['InsiderNumber'] conn = win32com.client.Dispatch(r'ADODB.Connection') conn.Open(dns) rs = win32com.client.Dispatch('ADODB.Recordset') rs.Open(sql, conn, 1, 3) while not rs.EOF: d = { } d['InsiderMoney'] = string.atof(str(rs('InsiderMoney')).strip()) d['SCardType'] = string.atoi(str(rs('SCardType')).strip()) rs.MoveNext() rs.Close() conn.Close() if d: d['type'] = 'cash' d['level'] = config.memtype[d['SCardType']] + 'CASH' temp = d else: return None tt = [] if self.queue.qsize() == 0: tt.append(temp['level']) if int(temp['InsiderMoney']) > config.switch_money: tt.append(str(int(temp['InsiderMoney']))) suffix = '.mp3' prefix = config.src for tem in tt: f = open((prefix + tem + suffix).encode('gbk'), 'rb') data = f.read() dm = muxer.Demuxer('mp3') frames = dm.parse(data) dec = acodec.Decoder(dm.streams[0]) r = dec.decode(data) snd = sound.Output(r.sample_rate, r.channels, 32, config.cashSpeaker) snd.play(r.data) while snd.isPlaying(): time.sleep(0.1) except BaseException: config.logger.error(traceback.format_exc())
def run(self): f = open(self.addr, 'rb') data = f.read(10000) dm = muxer.Demuxer(self.codec) frames = dm.parse(data) print len(frames) dec = acodec.Decoder(dm.streams[0]) frame = frames[0] r = dec.decode(frame[1]) #音频数据在 frame 数组的第二个元素中 print "sample_rate:%s , channels:%s " % (r.sample_rate, r.channels) snd = sound.Output(r.sample_rate, r.channels, sound.AFMT_S16_LE) if r: snd.play(r.data) while True: if not self.playing: break data = f.read(512) if len(data) > 0: r = dec.decode(data) if r: snd.play(r.data) else: while snd.isPlaying(): time.sleep(.5) break
def playTrack(track): cd.init() if cd.getCount() == 0: print 'There is no cdrom found. Bailing out...' return 0 c = cd.CD(0) props = c.getProperties() if props['type'] != 'AudioCD': print 'Media in %s has type %s, not AudioCD. Cannot read audio data.' % ( c.getName(), props['type']) return 0 tr0 = c.open(props['titles'][track - 1]) snd = sound.Output(44100, 2, sound.AFMT_S16_LE) s = ' ' while len(s): s = tr0.read(CHUNK_SIZE) snd.play(s) while snd.isPlaying(): time.sleep(.01)
def main(self): done = False while not done: yield 1 self.pause() while self.dataReady("inbox"): frame = self.recv("inbox") if not self.outputter or self.sample_rate != frame.sample_rate or self.channels != frame.channels: self.sample_rate = frame.sample_rate self.channels = frame.channels self.outputter = sound.Output(self.sample_rate, self.channels, self.audioformat) self.outputter.play( frame.data ) while self.dataReady("control"): msg = self.recv("control") if isinstance(msg, shutdownMicroprocess) or isinstance(msg, producerFinished): self.send(msg, "signal") done = True
def aPlayer( name ): global sampleFreqs, exit, snd # Open analyzer for a mono signal analyzer= sound.SpectrAnalyzer( 1, SAMPLES, NUM_FREQS ) resampler= None dec= acodec.Decoder( str.split( name, '.' )[ -1 ].lower() ) f= open( name, 'rb' ) snd= None s= f.read( 20000 ) while len( s ) and exit== 0: r= dec.decode( s ) if snd== None: print 'Opening sound with sample rate %d and channels %d' % ( r.sample_rate, r.channels ) snd= sound.Output( r.sample_rate, r.channels, sound.AFMT_S16_LE ) resampler= sound.Resampler( (r.sample_rate,r.channels), (r.sample_rate,1) ) if r and len( r.data ): s1= resampler.resample( r.data ) fTmp= analyzer.asBands( BANDS, s1 ) sampleFreqs.append( ( snd.getPosition()+ snd.getLeft(), fTmp ) ) snd.play( r.data ) pp= snd.getPosition() x= 0 while x< len( sampleFreqs ) and pp> sampleFreqs[ x ][ 0 ]: x+= 1 for i in range( 0, x- 1 ): del( sampleFreqs[ i ] ) s= f.read( 512 ) # Wait until complete all sounds while snd.isPlaying(): time.sleep( .05 ) exit= 1
def mp3Thread(self, s_name): import pymedia.audio.acodec as acodec import pymedia.muxer as muxer import pymedia.audio.sound as sound dm = muxer.Demuxer( str.split( str(sName), '.' )[ -1 ].lower() ) f = open( sName, 'rb' ) s = f.read(8192) fr = dm.parse(s) dec = acodec.Decoder(dm.streams[0]) r = dec.decode(s) snd= sound.Output(r.sample_rate, r.channels, sound.AFMT_S16_LE) while len(s) > 0: if self.stop_mp3: break if r: snd.play(r.data) s = f.read(512) try: r = dec.decode(s) except: break while snd.is_playing(): time.sleep(.05) self.is_playing = False
def __init__(self, sample_rate=44100, channels=2, format="S16_LE"): """x.__init__(...) initializes x; see x.__class__.__doc__ for signature""" super(_Output,self).__init__(queuelengths=20) pformat = format2PyMediaFormat[format] self.snd = sound.Output(sample_rate, channels, pformat)
def voiceRecorderPlayer(secs, delay, interval, name): # Turn on the microphone input open(name, 'wb').close() mixer = sound.Mixer() controls = mixer.getControls() micControls= filter( lambda x: \ x[ 'connection' ]== 'Microphone' and \ x[ 'destination' ]== 'Recording Control' and \ x[ 'name' ].count( 'Volume' )> 0, controls ) if len(micControls): micControls[0]['control'].setActive() print 'Setting microphone input as active' # Minimum set of parameters we need to create Encoder cparams = { 'id': acodec.getCodecID('mp3'), 'bitrate': 128000, 'sample_rate': 44100, 'channels': 2 } ac = acodec.Encoder(cparams) dm = muxer.Demuxer('mp3') dc = acodec.Decoder(cparams) sndIn = sound.Input(44100, 2, sound.AFMT_S16_LE) sndOut = sound.Output(44100, 2, sound.AFMT_S16_LE) sndIn.start() bytesWritten = 0 bytesRead = 0 t = time.time() paused = False # Loop until recorded position greater than the limit specified while sndIn.getPosition() <= secs: s = sndIn.getData() if s and len(s): f = open(name, 'ab') for fr in ac.encode(s): # We definitely should use mux first, but for # simplicity reasons this way it'll work also f.write(fr) bytesWritten += len(fr) f.close() else: # 1/10 of the second buffer for playback if sndOut.getLeft() < 0.1 and not paused: if bytesRead < bytesWritten + READ_CHUNK: f = open(name, 'rb') f.seek(bytesRead) s = f.read(READ_CHUNK) f.close() bytesRead += len(s) frames = dm.parse(s) if frames: for fr in frames: r = dc.decode(fr[1]) if r and r.data: sndOut.play(r.data) else: time.sleep(.01) # See if pause should be working i = int((time.time() - t) % (interval + delay)) paused = i > interval # Stop listening the incoming sound from the microphone or line in sndIn.stop()