def __init_encoder(self): # Minimum set of parameters we need to create Encoder encode_parameters = {'id': acodec.getCodecID('mp3'), 'bitrate': 128000, 'sample_rate': 44100, 'channels': 2} self.encoder = acodec.Encoder(encode_parameters)
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(0.003) # print 'boo' # Stop listening the incoming sound from the microphone or line in snd.stop()
def voiceRecorder(self, initUI, secs, channels, name): f = open(name, 'wb') # Minimum set of parameters we need to create Encoder cparams = { 'id': acodec.getCodecID('mp3'), 'bitrate': 138000, 'sample_rate': 44100, 'channels': channels } ac = acodec.Encoder(cparams) snd = sound.Input(44100, channels, 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, codec, bitrate, sample_rate, channels, **otherparams): super(AudioEncoder,self).__init__() params = { 'id' : acodec.getCodecID(codec), 'bitrate' : bitrate, 'sample_rate' : sample_rate, 'channels' : channels } params.update(otherparams) self.params = params self.codec = codec
def __init__(self, codec, bitrate, sample_rate, channels, **otherparams): super(AudioEncoder, self).__init__() params = { 'id': acodec.getCodecID(codec), 'bitrate': bitrate, 'sample_rate': sample_rate, 'channels': channels } params.update(otherparams) self.params = params self.codec = codec
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, codec, bitrate, sample_rate, channels, **otherparams): """x.__init__(...) initializes x; see x.__class__.__doc__ for signature""" super(Encoder,self).__init__() codec = codec2PyMediaCodec[codec] params = { 'id' : acodec.getCodecID(codec), 'bitrate' : bitrate, 'sample_rate' : sample_rate, 'channels' : channels } params.update(otherparams) self.params = params self.codec = codec
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 __init__(self, codec, bitrate, sample_rate, channels, **otherparams): """x.__init__(...) initializes x; see x.__class__.__doc__ for signature""" super(Encoder, self).__init__() codec = codec2PyMediaCodec[codec] params = { 'id': acodec.getCodecID(codec), 'bitrate': bitrate, 'sample_rate': sample_rate, 'channels': channels } params.update(otherparams) self.params = params self.codec = codec
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 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()
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 voiceRecorder( secs, channels, name ): f= open( name, 'wb' ) # Minimum set of parameters we need to create Encoder cparams= { 'id': acodec.getCodecID( 'mp3' ), 'bitrate': 138000, 'sample_rate': 44100, 'channels': channels } ac= acodec.Encoder( cparams ) snd= sound.Input( 44100, channels, 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 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 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()
"Name of the last recording folder" id= "" "An id which could be received and send from the socket" urlserver= "" "Default URL of the audiovideocours server containing the submit form" samplingFrequency= 48000 "Default sampling frequency for audio recording" stopKey= "F8" "Default key to start/stop recording if you don't have the serial Kb" socketEnabled=False "To listen to a socket for eventual orders from a server" portNumber= 3737 "Socket port to listen to for server orders (sending an eventual ID also)" READ_CHUNK= 512 "Chunck size for pymedia audio reading" cparams= { 'id': acodec.getCodecID( 'mp3' ), 'bitrate': 128000, 'sample_rate': 48000 , 'channels': 1 } "Set of parameters for the pymedia audio Encoder" nameRecord="enregistrement-micro.mp3" "Dafault name of the audio recording" tryFocus=False "A boolean var to inform when the app is trying to get focus back on a frame" serialKeyboard=False "To indicate if the special keyboard must be used" keyboardPort=0 "Serial port number to use for serial keyboard" videoprojectorInstalled=False "To indicate if a videoprojector bust be used on a serial plug" videoprojectorPort=1
f = file('output.avi', 'wb') # output file # decode a frame of the mp3 just to get its params, which are then used during muxing with the video dm = muxer.Demuxer('mp3') frames = dm.parse( mp3data ) # demux the data into sub streams, in this case, there's only the audio stream frame0 = frames[ 0] # get the first frame of the sub streams. This is a (stream id, data) tuple dec = acodec.Decoder(dm.streams[frame0[0]]) # open a decoder decodedframe0 = dec.decode(frame0[1]) # decode it aparams = { 'channels': decodedframe0.channels, 'sample_rate': decodedframe0.sample_rate, 'bitrate': decodedframe0.bitrate, 'id': acodec.getCodecID('mp3') } width = m.ncellswide * enlargex height = m.ncellshigh * enlargex vparams = { 'type': 0, 'gop_size': 12, 'max_b_frames': 0, 'frame_rate_base': 1, 'frame_rate': 50, 'width': width, 'height': height, 'deinterlace': 0, 'bitrate': 300000, # normally 2700000 for a framerate of 2997/125 Hz
mp3file = file(mp3name, 'rb') mp3data = mp3file.read() # read the whole file in mp3file.close() f = file('output.avi', 'wb') # output file # decode a frame of the mp3 just to get its params, which are then used during muxing with the video dm = muxer.Demuxer('mp3') frames = dm.parse(mp3data) # demux the data into sub streams, in this case, there's only the audio stream frame0 = frames[0] # get the first frame of the sub streams. This is a (stream id, data) tuple dec = acodec.Decoder(dm.streams[ frame0[0] ]) # open a decoder decodedframe0 = dec.decode(frame0[1]) # decode it aparams = {'channels': decodedframe0.channels, 'sample_rate': decodedframe0.sample_rate, 'bitrate': decodedframe0.bitrate, 'id': acodec.getCodecID('mp3') } width = m.ncellswide * enlargex height = m.ncellshigh * enlargex vparams = {'type': 0, 'gop_size': 12, 'max_b_frames': 0, 'frame_rate_base': 1, 'frame_rate': 50, 'width': width, 'height': height, 'deinterlace': 0,
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()