def clean_file(self): data = self.cleaned_data['file'] if not hasattr(data, 'temporary_file_path'): logging.error("uploaded file was kept in memory") if dscan.is_configured() and hasattr(data, 'temporary_file_path'): file = data.temporary_file_path() df = dscan.ScanFile(file) if not df.readable: raise forms.ValidationError( "Unsupported audio format! Check the FAQ to see what's accepted" ) #I dropped the bitrate requirement. nothing keeps people from reencoding shitty files # which will further reduce quality. also with ogg and aac, lower bitrates are more common #if df.bitrate < 128 and df.bitrate != 0: # raise forms.ValidationError("We only accept audio with a bitrate of 128 kbps or higher") #how the hell pymand finds the file without path is a mystery to me if not dscan.is_configured(): import mad mf = mad.MadFile(data) bitrate = mf.bitrate() / 1000 layer = mf.layer() if bitrate < 128 or layer != 3: raise forms.ValidationError( "We only accept mpeg layer 3 (MP3) encoded files with bitrate of 128 kbps or higher" ) return data
def play(self, fp): import mad, ao backend = self.backend if backend is None: import sys backend = { 'darwin': 'macosx', 'win32': 'wmm', 'linux2': 'alsa' }.get(sys.platform) if backend is None: raise Exception("Can't guess a usable libao baceknd." "If you know a backend that may work on your system then" "you can specify it using the backend options parameter.") mf = mad.MadFile(fp) dev = ao.AudioDevice(backend) while True: buf = mf.read() if buf is None: break dev.play(buf, len(buf))
def main(): # Open the audio device. dev = ao.AudioDevice('pulse', rate=44100) # Create a wrapper object. wrap = mywrapper() # Open an MP3 file and read in all the data. # For you, this data will come in over the network from the server. f = open(sys.argv[1], 'r') data = f.read() f.close() # Hand off the data to the wrapper object and use it to create a new MAD # library decoder. For your client, you will be appending chunks of data # to the end of wrap.data in your receiver thread while the player thread # is removing and playing data from the front of it. wrap.data = data wrap.mf = mad.MadFile(wrap) # Play the file. while True: buf = wrap.mf.read() if buf is None: # eof break dev.play(buffer(buf), len(buf))
def load_mp3_sample( fname, always_two_channels=True ): #looks like latest pymad is always returning two channels ? this is quick fix mf = mad.MadFile(fname) name = fname if isinstance(fname, types.StringTypes) else '<stream>' logger.debug( 'loading mp3 file %s : rate %d, layer %d, mode %d, total time %d' % (name, mf.samplerate(), mf.layer(), mf.mode(), mf.total_time())) a = numpy.array([], dtype=numpy.int16) #TODO: this is not very effective while 1: #read frame audio = mf.read() if audio is None: break a = numpy.append(a, numpy.frombuffer(audio, dtype=numpy.int16)) #a=numpy.fromstring(str(sample)[3:], dtype=numpy.int16) logger.debug('Lodaded %d words' % len(a)) if mf.mode() in (3, 2) or always_two_channels: a.shape = -1, 2 a = numpy.mean(a, 1) a = numpy.around(a) a = a.astype(numpy.int16, casting="unsafe") return a, mf.samplerate()
def play(self): try: mf = mad.MadFile(self.f) except IOError: print "Error opening file %s for playing" % self.f sys.exit(1) if self.seek_time > 5000: #seeking is broken a bit, we have to flush the buffer by reading mf.seek_time(self.seek_time - 5000) for i in range(100): mf.read() #dev = ao.AudioDevice('alsa', rate=mf.samplerate()) dev = alsaaudio.PCM(device='default') dev.setrate(mf.samplerate()) iSave = 0 why_stopped = '' print "Starting to play" while True: buf = mf.read() if (buf is None): if buf is None: why_stopped = 'finished' break dev.write(buffer(buf)) iSave += 1 if iSave == 100: self.seek_time = mf.current_time() print "Finished playing" if why_stopped == 'finished': self.seek_time = 0
def play(self): """ Main function that plays a 7digital url """ if self.url == '': return if self.is_playing: return self.is_playing = True self.do_stop = False self.printinfo('start playing url:',self.url) #urldata = urllib.urlretrieve(self.url) urlstream = urllib2.urlopen(self.url) mf = mad.MadFile(urlstream) # if bits=32, too fast self.dev = ao.AudioDevice('alsa', bits=16, rate=mf.samplerate(),channels=2) buf = mf.read() t1 = time.time() while buf != None and not self.do_stop: # len(buf) is 4608 self.dev.play(buf, len(buf)) buf = mf.read() self.do_stop = False self.is_playing = False tlag = time.time() - t1 self.printinfo('done playing url after',str(int(tlag)),'seconds')
def __init__(self, filename): """Construct a Player. :param filename """ self._command = ["/usr/bin/vlc", "--intf", "dummy", "--play-and-exit", filename] self._length = mad.MadFile(filename).total_time()
def _create_stream(filename, checks): if filename[-3:] in ['wav','WAV']: wf = wave.open(filename, 'rb') if checks: assert(wf.getsampwidth() == 2) assert(wf.getnchannels() == gchannels) assert(wf.getframerate() == gsamplerate) # create stream object stream = _Stream() def str_read(): return wf.readframes(4096) # give the stream object a read() method stream.read = str_read def str_seek_time(t): if t == 0: wf.rewind() assert(False) # unsupported for WAV streams stream.seek_time = str_seek_time return stream # Here's how to do it for MP3 if filename[-3:] in ['mp3','MP3']: mf = mad.MadFile(filename) if checks: assert(gchannels == 2) # MAD always returns stereo assert(mf.samplerate() == gsamplerate) stream = mf return stream assert(False) # filename must have wav or mp3 extension
def play_thread_func(wrap, cond_filled, dev): currently_playing_song = wrap.song_id while True: # print "it is stop in while loop 1x" cond_filled.acquire() while True: # print "it is stop in while loop 2" if wrap.new_data_added: print "new data added!" break print "wait!" cond_filled.wait() # sleep until new data added # play the song, play just a lit bit each time! wrap.new_data_added = False # currently_playing_song = wrap.song_id cond_filled.release() wrap.mf = mad.MadFile(wrap) # Play the song, play what we have now. while True: buf = wrap.mf.read() if buf is None: # eof print "buf is None" break if wrap.method == 'STOP': print "STOP!" break # if wrap.song_id != currently_playing_song: # print "Play a different song!" # buf = '' # currently_playing_song = wrap.song_id dev.play(buffer(buf), len(buf))
def get_media_duration(media_path): mf = mad.MadFile(str(media_path.joinpath('album.mp3'))) track_length_miliseconds = mf.total_time() album_duration = track_length_miliseconds * 1000 end_album = time.strftime('%H:%M:%S', time.gmtime(album_duration)) return end_album
def recv_thread_func(wrap, cond_filled, sock, download_dir): response = None while True: # TODO data = sock.recv(READ_BUFFER) #print "client receiving:",data\ if "+OK " in data: wrap.data = '' wrap.mf = mad.MadFile(wrap) idx = data.find("+OK ") data = data[idx:] if "+NO " in data: idx = data.find("+NO ") data = data[idx:] if data[4:8] in ["list", "play", "erro"]: response = data[4:8] if response != "play": data = data[9:] else: i = 9 id = "" while data[i].isdigit(): id += data[i] i += 1 current_play = "" while data[i] != "\r" and data[i + 1] != "\n": current_play += data[i] i += 1 print "current playing:", current_play playing[0] = True if response == "list": print data[:-3] if response == "play": #print "play:",current_play cond_filled.acquire() wrap.data += data cond_filled.notify() cond_filled.release() if response == 'erro': if data[:3] == "out": print "Oops!song number/name is not in the list, try again!" if data[:3] == "Unk": print "Oops! Unkown error!" if data[-4:] == "\r\n\r\n": #download the whole song if response == "play": download_mp3(current_play, wrap.data, download_dir) downloaded[id] = current_play #print "current downloaded:",downloaded response = None
def generate_list(name="songs_list.m3u", path=".", sort=True, walk=False): """ generates the M3U playlist with the given file name le(name, "w and in the given path """ fp = None try: try: if walk: # recursive version mp3_list = [os.path.join(root, i) for root, dirs, files in os.walk(path) for i in files \ if i[-3:] == "mp3"] else: # non recursive version mp3_list = [i for i in os.listdir(path) if i[-3:] == "mp3"] #print mp3_list if sort: mp3_list.sort() fp = file(name, "w") fp.write(FORMAT_DESCRIPTOR + "\n") for track in mp3_list: if not walk: track = os.path.join(path, track) else: track = os.path.abspath(track) # open the track with mad and ID3 mf = mad.MadFile(track) id3info = ID3.ID3(track) # M3U format needs seconds but # total_time returns milliseconds # hence i convert them in seconds track_length = mf.total_time() / 1000 # get the artist name and the title artist, title = id3info.artist, id3info.title # if artist and title are there if artist and title: fp.write(RECORD_MARKER + ":" + str(track_length) + "," +\ artist + " - " + title + "\n") else: fp.write(RECORD_MARKER + ":" + str(track_length) + "," +\ os.path.basename(track)[:-4] + "\n") # write the fullpath fp.write(track + "\n") except (OSError, IOError), e: print e finally: if fp: fp.close()
def __init__(self, filename): self.filename = filename import mad try: self.mf = mad.MadFile(filename) except IOError, e: if e.errno == ENOENT: raise McFooBackendFileDoesNotExist else: raise
def getDuration(path): import mad mf = mad.MadFile(path) ms = mf.total_time() sec = ms / 1000 min = sec / 60 sec %= 60 return (min, sec)
def play(self, do_speak=True): files = self.get_files() if do_speak: self.speak(self.seek_time, self.file_index) why_stopped = 'finished' while self.file_index < len(files) and why_stopped == 'finished': if self.isRadio: f = self.get_radio_file() else: f = self.get_audio_file(files) mf = mad.MadFile(f) if self.seek_time > 5000: #seeking is broken a bit, we have to flush the buffer by reading mf.seek_time(self.seek_time - 5000) for i in range(100): mf.read() dev = ao.AudioDevice('alsa', rate=mf.samplerate()) iSave = 0 why_stopped = '' logger.info("Starting to play") self.msg_queue.put(PlayerMsg('started', self.isRadio)) while True: buf = mf.read() if (buf is None) or self.pipe.poll(): if buf is None: why_stopped = 'finished' break dev.play(buf, len(buf)) #we cannot save in this process, we would get buffer underrun if not self.isRadio: iSave += 1 if iSave == 100: self.seek_time = mf.current_time() self.msg_queue.put( SavePosMsg((self.seek_time, self.file_index, self.folder_name))) iSave = 0 if not self.isRadio: self.seek_time = mf.current_time() if why_stopped == 'finished': self.seek_time = 0 self.file_index += 1 #now the whole system may be already quitting and message queue will not be inspected, so we must save position ourselves if not self.isRadio: conn = sqlite3.connect('player.db') conn.execute( 'update lastpos set position = ?, fileindex = ? where foldername = ?', (self.seek_time, self.file_index % len(files), self.folder_name)) conn.commit() #if we finished the last track, we shall mark it as complete (this is purely statistical, is not used by the program) if (self.seek_time == 0) and (self.file_index == len(files)): conn.execute( 'update lastpos set completed = completed + 1 where foldername = ?', (self.folder_name, )) conn.commit()
def get_duration_from_url(url): print "Downloading %s" % url tmp = tempfile.mktemp(suffix=".mp3") try: file(tmp, "wb").write(urllib.urlopen(url).read()) return int(mad.MadFile(tmp).total_time() / 1000) finally: if os.path.exists(tmp): os.unlink(tmp)
def _connect(self, url): try: # TODO: there's no way to control how long to wait here. It can potentially # block forever if the socket connection is established but the server then # doesn't respond to the request (unlikely, but not good) r = urllib.urlopen(url) except (httplib.HTTPException, IOError) as e: raise SourceError('stream error: {}'.format(e)) headers = r.info() self.debug('response headers: {}', headers) if r.getcode() != 200: raise SourceError('stream error: HTTP response code {}'.format( r.getcode())) content_type = headers.get('content-type') if content_type != 'audio/mpeg': raise SourceError( 'unsupported stream type: {}'.format(content_type)) transfer_encoding = headers.get('transfer-encoding') if transfer_encoding: raise SourceError( 'unsupported transfer encoding: {}'.format(transfer_encoding)) content_encoding = headers.get('content-encoding') if transfer_encoding: raise SourceError( 'unsupported content encoding: {}'.format(content_encoding)) # Take over the socket to do raw streaming ourselves, so the request object # can be closed self._socket = socket.fromfd(r.fileno(), socket.AF_INET, socket.SOCK_STREAM) r.close() self._poll = select.poll() self._poll.register(self._socket, select.POLLIN) try: mf = mad.MadFile(self) except RuntimeError as e: raise SourceError('mpeg decoding error: {}'.format(e)) if self._response_error: raise SourceError('http streaming error: {}'.format( self._response_error)) self.debug('stream rate: {} Hz, layer: {}, bitrate: {}', mf.samplerate(), mf.layer(), mf.bitrate()) self._format = model.Format(rate=mf.samplerate(), big_endian=(sys.byteorder != 'little')) self._mpeg = mf
def PlayIt(self, filename): #print filename #filename = unicode(filename) self.mf = mad.MadFile(filename) self.pya = pyaudio.PyAudio() p = self.pya self.stream = p.open(format=p.get_format_from_width(pyaudio.paInt32), channels=2, rate=self.mf.samplerate(), output=True) self.data = self.NextData() self.state = 'Play'
def LoadSet(u): mf = mad.MadFile(u) if mf.layer() == mad.LAYER_I: print "MPEG Layer I" elif mf.layer() == mad.LAYER_II: print "MPEG Layer II" elif mf.layer() == mad.LAYER_III: print "MPEG Layer III" else: print "unexpected layer value" if mf.mode() == mad.MODE_SINGLE_CHANNEL: print "single channel" elif mf.mode() == mad.MODE_DUAL_CHANNEL: print "dual channel" elif mf.mode() == mad.MODE_JOINT_STEREO: print "joint (MS/intensity) stereo" elif mf.mode() == mad.MODE_STEREO: print "normal L/R stereo" else: print "unexpected mode value" if mf.emphasis() == mad.EMPHASIS_NONE: print "no emphasis" elif mf.emphasis() == mad.EMPHASIS_50_15_US: print "50/15us emphasis" elif mf.emphasis() == mad.EMPHASIS_CCITT_J_17: print "CCITT J.17 emphasis" else: print "unexpected emphasis value" print "bitrate %lu bps" % mf.bitrate() print "samplerate %d Hz" % mf.samplerate() #millis = mf.total_time() #secs = millis / 1000 #print "total time %d ms (%dm%2ds)" % (millis, secs / 60, secs % 60) #dev = ao.AudioDevice('alsa', bits=16, rate=mf.samplerate()) samples = [] while 1: buf = mf.read() if (buf is None) or (len(buf) <= 0) or (len(samples) > (44100*60)): print "DONE" break for i in xrange(0, len(buf), 4): #print "ADDING SAMPLE:", i, "SAMPLES:", len(samples) sample = struct.unpack_from("hh", buf, i) samples.append((sample[0]+sample[0])/2) print "DONE READING MP3" return samples
def play_thread_func(wrap, cond_filled, dev): while True: cond_filled.acquire() cond_filled.wait() try: wrap.mf = mad.MadFile(wrap) while wrap.state == 1: buf = wrap.mf.read() if buf is None: break dev.play(buffer(buf), len(buf)) finally: cond_filled.release()
def get_duration(url): ext = os.path.splitext(url)[1] if ext != ".mp3": return None tmp = tempfile.mktemp(suffix=ext) try: req = urllib2.urlopen(url) file(tmp, "wb").write(req.read()) return int(mad.MadFile(tmp).total_time() / 1000) finally: if os.path.exists(tmp): os.unlink(tmp)
def _PlayFile(self, filename): self._logger.info('Playing %s' % filename) mf = mad.MadFile(filename) dev = ossaudiodev.open('w') dev.speed(mf.samplerate()) dev.setfmt(ossaudiodev.AFMT_S16_LE) dev.channels(2) while True: if self._file_queue.qsize(): break buf = mf.read() if buf is None: break dev.write(buf)
def play_mp3(self, filename): mf = mad.MadFile(filename) with tempfile.NamedTemporaryFile(suffix='.wav') as f: wav = wave.open(f, mode='wb') wav.setframerate(mf.samplerate()) wav.setnchannels(1 if mf.mode() == mad.MODE_SINGLE_CHANNEL else 2) # 4L is the sample width of 32 bit audio wav.setsampwidth(4) frame = mf.read() while frame is not None: wav.writeframes(frame) frame = mf.read() wav.close() self.play(f.name)
def mp3_to_wave(self, filename): mf = mad.MadFile(filename) with tempfile.SpooledTemporaryFile() as f: wav = wave.open(f, mode='wb') wav.setframerate(mf.samplerate()) wav.setnchannels(1 if mf.mode() == mad.MODE_SINGLE_CHANNEL else 2) # 4L is the sample width of 32 bit audio wav.setsampwidth(4) frame = mf.read() while frame is not None: wav.writeframes(frame) frame = mf.read() wav.close() f.seek(0) data = f.read() return data
def play_thread_func(wrap, cond_filled, dev): wrap.mf = mad.MadFile(wrap) while True: # if wrap.slow_start: # sleep(5) # cond_filled.acquire() # wrap.slow_start = False # cond_filled.release() if wrap.ready and not wrap.stopped: cond_filled.acquire() buf = wrap.mf.read() cond_filled.release() if buf is None: # eof continue else: dev.play(buffer(buf), len(buf))
def play(self, fp): import mad, pyaudio mf = mad.MadFile(fp) # open stream p = pyaudio.PyAudio() stream = p.open(format=p.get_format_from_width(pyaudio.paInt32), channels=2, rate=mf.samplerate(), output=True) data = mf.read() while data != None: stream.write(data) data = mf.read() stream.close() p.terminate()
def play_mp3(cls, filename): f = mad.MadFile(filename) p = pyaudio.PyAudio() # open stream stream = p.open(format=p.get_format_from_width(pyaudio.paInt32), channels=2, rate=f.samplerate(), output=True) data = f.read() while data: stream.write(data) data = f.read() stream.stop_stream() stream.close() p.terminate()
def play(u): mf = mad.MadFile(u) if mf.layer() == mad.LAYER_I: print "MPEG Layer I" elif mf.layer() == mad.LAYER_II: print "MPEG Layer II" elif mf.layer() == mad.LAYER_III: print "MPEG Layer III" else: print "unexpected layer value" if mf.mode() == mad.MODE_SINGLE_CHANNEL: print "single channel" elif mf.mode() == mad.MODE_DUAL_CHANNEL: print "dual channel" elif mf.mode() == mad.MODE_JOINT_STEREO: print "joint (MS/intensity) stereo" elif mf.mode() == mad.MODE_STEREO: print "normal L/R stereo" else: print "unexpected mode value" if mf.emphasis() == mad.EMPHASIS_NONE: print "no emphasis" elif mf.emphasis() == mad.EMPHASIS_50_15_US: print "50/15us emphasis" elif mf.emphasis() == mad.EMPHASIS_CCITT_J_17: print "CCITT J.17 emphasis" else: print "unexpected emphasis value" print "bitrate %lu bps" % mf.bitrate() print "samplerate %d Hz" % mf.samplerate() sys.stdout.flush() #millis = mf.total_time() #secs = millis / 1000 #print "total time %d ms (%dm%2ds)" % (millis, secs / 60, secs % 60) dev = ao.AudioDevice(0, rate=mf.samplerate()) while 1: buffy = mf.read() if buffy is None: break dev.play(buffy, len(buffy))
def play_thread_func(wrap, cond_filled, dev): while True: cond_filled.acquire() while True: if wrap.ctp_flag == True: break cond_filled.wait( ) # just wait to play, either buffer enough, or new packet wrap.ctp_flag = False cond_filled.release() wrap.mf = mad.MadFile(wrap) while True: buf = wrap.mf.read() if wrap.method == 'STOP': break if buf is None: break dev.play(bytes(buf), len(buf))
def mad_match(apikey, path, metadata=None): """Uses MAD to decode an MPEG audio file and perform a match. Requires the pymad module. """ import mad f = mad.MadFile(path) # Get number of channels. if f.mode() == mad.MODE_SINGLE_CHANNEL: channels = 1 elif f.mode() in (mad.MODE_DUAL_CHANNEL, mad.MODE_JOINT_STEREO, mad.MODE_STEREO): channels = 2 else: channels = 2 return match(apikey, _readblocks(f), f.samplerate(), f.total_time() / 1000, channels, metadata)