def voiceRecorder(secs, name): f = open(name, 'wb') # 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) snd = sound.Input(44100, 2, sound.AFMT_S16_LE) snd.start() # Loop until recorded position greater than the limit specified while snd.getPosition() <= secs: s = snd.getData() if s and len(s): 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) else: time.sleep(.003) # Stop listening the incoming sound from the microphone or line in snd.stop()
def run(self): f = open(self.file_name, 'wb') # Minimum set of parameters we need to create Encoder # getCodecID() cparams = { 'id': acodec.getCodecID('mp3'), 'bitrate': self.bitrate, 'sample_rate': 44100, 'channels': 2 } ac = acodec.Encoder(cparams) #print sound.getODevices() #print sound.getIDevices() snd = sound.Input(44100, 2, sound.AFMT_S16_LE, 0) snd.start() # Loop until recorded position greater than the limit specified #while snd.getPosition()<= secs: while self.status == 'record': #print snd.getPosition() s = snd.getData() if s and len(s): 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) else: time.sleep(.003) #print 'boo' # Stop listening the incoming sound from the microphone or line in snd.stop()
def recodeAudio(fName, fOutput, type, bitrate=None): # ------------------------------------ import pymedia.audio.acodec as acodec import pymedia.muxer as muxer # Open demuxer dm = muxer.Demuxer(fName.split('.')[-1].lower()) f = open(fName, 'rb') s = f.read(90000) dec = enc = mx = None print 'Recoding %s into %s' % (fName, fOutput) while len(s): frames = dm.parse(s) if frames: for fr in frames: # Assume for now only audio streams if dec == None: # Open decoder dec = acodec.Decoder(dm.streams[fr[0]]) print 'Decoder params:', dm.streams[fr[0]] # Decode audio frame r = dec.decode(fr[1]) if r: if bitrate == None: bitrate = r.bitrate # Open muxer and encoder if enc == None: params = { 'id': acodec.getCodecID(type), 'bitrate': bitrate, 'sample_rate': r.sample_rate, 'channels': r.channels } print 'Encoder params:', params mx = muxer.Muxer(type) stId = mx.addStream(muxer.CODEC_TYPE_AUDIO, params) enc = acodec.Encoder(params) fw = open(fOutput, 'wb') ss = mx.start() fw.write(ss) enc_frames = enc.encode(r.data) if enc_frames: for efr in enc_frames: ss = mx.write(stId, efr) if ss: fw.write(ss) s = f.read(100000) f.close() if fw: if mx: ss = mx.end() if ss: fw.write(ss) fw.close()
def __init__(self, audio_id, out_dir='.'): threading.Thread.__init__(self) self.stop = threading.Event() self.recording = threading.Event() self.stopped = threading.Event() self.filename = out_dir+'/'+audio_id+'.mp3' self.encoder = acodec.Encoder({ 'id': acodec.getCodecID('mp3'), 'bitrate': 96000, 'sample_rate': 44100, 'channels': 2 }) self.recorder = sound.Input(44100, 2, sound.AFMT_S16_LE)
def run(self): print "recording to", self.name self.f = open(self.name, 'wb') # Minimum set of parameters we need to create Encoder cparams = { 'id': acodec.getCodecID('mp3'), 'bitrate': 128000, 'sample_rate': 44100, 'channels': 1 } self.ac = acodec.Encoder(cparams) self.snd = sound.Input(44100, 1, sound.AFMT_S16_LE) self.mux = muxer.Muxer("mp3") self.stream_index = self.mux.addStream(muxer.CODEC_TYPE_AUDIO, self.ac.getParams()) block = self.mux.start() if block: self.f.write(block) # Loop until Ctrl-C pressed or finished set from outside self.finished = False thread = threading.Thread(target=self.record) thread.start() try: while not self.finished: time.sleep(.003) except KeyboardInterrupt: self.finished = True print "finishing recording to", self.name # Stop listening the incoming sound from the microphone or line in thread.join() footer = self.mux.end() if footer is not None: self.f.write(footer) self.f.close() print "finished recording to", self.name print "snipping leading zeroes..." f = open(self.name, "rb") buffer = f.read() f.close() buffer = buffer.lstrip(chr(0)) f = open(self.name, "wb") f.write(buffer) f.close() print "snipped leading zeroes"
def _encode(self, filetype): cparams = { 'id': acodec.getCodecID(filetype), 'bitrate': 128000, 'sample_rate': self.samplerate, 'channels': self.channels } out_fp = open(self.output_file, 'wb') ac = acodec.Encoder(cparams) self._recording = True self.input.start() while self._recording: s = self.input.getData() if s and len(s): for fr in ac.encode(s): out_fp.write(fr) else: time.sleep(0.03) self.input.stop() self.input = None
def main(self): mux = muxer.Muxer(self.codec) streamId = mux.addStream(muxer.CODEC_TYPE_AUDIO, self.params) enc = acodec.Encoder(self.params) data = mux.start() if data: self.send(data, "outbox") shutdown = False data = "" MINSIZE = 4096 while self.anyReady() or not shutdown: while self.dataReady("inbox"): newdata = self.recv("inbox") data = data + newdata['audio'] if len(data) >= MINSIZE: frames = enc.encode(data) for frame in frames: muxed = mux.write(streamId, frame) if muxed: self.send(muxed, "outbox") data = "" while self.dataReady("control"): msg = self.recv("control") if isinstance(msg, (producerFinished, shutdownMicroprocess)): shutdown = True self.send(msg, "signal") if not shutdown: self.pause() yield 1 data = mux.end() if data: self.send(data, "outbox")
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()
def encodeVideo(fName, fOutFile, codecName): # ------------------------------------ import time, traceback import pymedia.muxer as muxer import pymedia.audio.acodec as acodec import pymedia.video.vcodec as vcodec format = fName.split('.')[-1].lower() dm = muxer.Demuxer(format) f = open(fName, 'rb') fw = open(fOutFile, 'wb') s = f.read(390000) r = dm.parse(s) print "Streams found:", dm.streams ss = filter(lambda x: x['type'] == muxer.CODEC_TYPE_AUDIO, dm.streams) if len(ss) == 0: raise 'No suitable audio streams in a file' a_id = ss[0]['index'] ac = acodec.Decoder(ss[0]) ss = filter(lambda x: x['type'] == muxer.CODEC_TYPE_VIDEO, dm.streams) if len(ss) == 0: raise 'No video streams in a file' v_id = ss[0]['index'] vc = vcodec.Decoder(ss[0]) #create muxer mux = muxer.Muxer('ts') header = a_id1 = v_id1 = None m_data = [] while len(s): for d in r: if d[0] == v_id: vfr = vc.decode(d[1]) if vfr: if v_id1 == None: params = vc.getParams() params['id'] = vcodec.getCodecID(codecName) if codecName == 'mpeg1video': params['bitrate'] = 2700000 elif codecName == 'mpeg2video': params['bitrate'] = 9800000 print 'Video: encoder params ', params vc1 = vcodec.Encoder(params) v_id1 = mux.addStream(muxer.CODEC_TYPE_VIDEO, vc1.getParams()) print "video stream id in muxer:", v_id1 s1 = vc1.encode(vfr) m_data.append((v_id1, s1)) elif d[0] == a_id: frame = ac.decode(d[1]) if a_id1 == None: params = { 'channels': frame.channels, 'sample_rate': frame.sample_rate, 'bitrate': frame.bitrate, 'id': acodec.getCodecID('mp3') } print 'Audio: encoder params ', params ac1 = acodec.Encoder( params) #or any other supported audio encoder a_id1 = mux.addStream(muxer.CODEC_TYPE_AUDIO, ac1.getParams()) print "audio stream id in muxer:", a_id1 encFrames = ac1.encode(frame.data) for fr in encFrames: m_data.append((a_id1, fr)) # We know that video and audio exists already if a_id1 != None and v_id1 != None: # Start header when all streams are captured if header == None: header = mux.start() fw.write(header) for st_id, ss in m_data: s1 = mux.write(st_id, ss) if s1: fw.write(s1) m_data = [] s = f.read(100000) r = dm.parse(s) fw.close()