def aplayer( name, card, rate, tt ):
  import pymedia.muxer as muxer, pymedia.audio.acodec as acodec, pymedia.audio.sound as sound
  import time

  analyzer = sound.SpectrAnalyzer(1, 500, 2)
  
  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 )

            #ftmp = analyzer.asBands(1, data)
            ftmp = analyzer.asFrequencies( data )
            for ft in ftmp:
                print ft[1]*10
            
    if tt> 0:
      if snd and snd.getPosition()> tt:
        break
    
    s= f.read( 512 )

  while snd.isPlaying():
    time.sleep( .05 )
Esempio n. 2
0
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)
Esempio n. 3
0
	def aplayer( self, card, rate, tt ):
	  dm= muxer.Demuxer( "mp3" )
	  snds= sound.getODevices()
	  get=urllib2.urlopen("http://douban.fm/j/mine/playlist")
	  data=get.read()
	  s=json.loads(data)
	  url=s["song"][1]["url"]
	  if card not in range( len( snds ) ):
		raise 'Cannot play sound to non existent device %d out of %d' % ( card+ 1, len( snds ) )
	  #f=urllib2.urlopen("http://zxc111.net/1.mp3")
	  f=urllib2.urlopen(url)
	  #f= open( name, 'rb' )
	  self.snd= resampler= dec= None
	  s= f.read(1024)
	  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 self.snd== None:
				print 'Opening sound with %d channels -> %s' % ( r.channels, snds[ card ][ 'name' ] )
				self.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 )
			  EMULATE=0
			  if EMULATE:
				# Calc delay we should wait to emulate self.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:
				self.snd.play( data )
		if tt> 0:
		  if snd and self.snd.getPosition()> tt:
			break
		
		s= f.read( 512 )

	  while self.snd.isPlaying():
		time.sleep( .05 )
Esempio n. 4
0
    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()
Esempio n. 5
0
def toca (name, card=0):
    import pymedia.muxer as muxer
    import pymedia.audio.acodec as acodec
    import pymedia.audio.sound as sound
    import time,wave
    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))
    ext = name.split('.')[-1].lower()
    if ext == 'wav':
        f = wave.open (name, 'rb')
        snd = sound.Output (f.getframerate(), f.getnchannels(), sound.AFMT_S16_LE, card)
        s= ' '
        while len(s):
            s = f.readframes (512)
            snd.play (s)
    else:
        dm = muxer.Demuxer (ext)
        f = open (name, 'rb')
        snd = dec = None
        s = f.read (32*1024)
        t = 0
        while len (s):
            frames = dm.parse (s)
            if frames:
                for fr in frames:
                    # Assume for now only audio streams
                    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 (r.sample_rate, r.channels, sound.AFMT_S16_LE, card)
                        snd.play (r.data)
              
            s = f.read (512)

    while snd.isPlaying():
        time.sleep (.05)
Esempio n. 6
0
   def audioPlayExtend(self, fileName, card, rate):
      '''play wav, mp3, wma and others file'''

      dm = muxer.Demuxer(str.split(fileName, '.')[-1].lower())
      snds = sound.getODevices()
      if card not in range(len(snds)):
         logger.error('Cannot play sound to non existent device %d out of %d' % (card+1, len(snds)))
      f = open(fileName, 'rb')
      global snd
      snd = resampler = dec = None
      s = f.read(32000)
      while len(s):
         frames = dm.parse(s)
         if frames:
            for fr in frames:
               # Assume for now only audio streams
               if dec == None:
                  logger.info('getInfo %s %s' % (dm.getInfo(), dm.streams))
                  dec = acodec.Decoder(dm.streams[fr[0]])
                  
               r = dec.decode(fr[1])
               if r and r.data:
                  if snd == None:
                     logger.info('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))
                        logger.info('Sound resampling %d->%d' % (r.sample_rate, r.sample_rate/rate))
                  data = r.data
                  if resampler:
                     data = resampler.resample(data)
                  snd.play(data)
         s = f.read(512)
      # The biggest trick for newbies is that snd.play() will return before playing of the chunk ends. 
      # It is so called 'asynchronous' mode of playing audio. 
      # If you want to wait until everything is finished, add this line:
      while snd.isPlaying():         
         time.sleep(.05)
Esempio n. 7
0
    def run(self):
        """ plays a god-damn song """

        #local mp3 playback
        print self.file_name.encode('utf-8')
        self.parent.current_song.status = 'loading'
        while os.path.isfile(self.file_name) != True:
            time.sleep(1)

        get_buffer = options.GetSetting('buffer-size-bytes',
                                        self.parent.FILEDB)
        if get_buffer != False:
            buffer_sz = int(get_buffer)
        else:
            buffer_sz = BUFFER_SIZE
        while os.path.getsize(self.file_name) < buffer_sz:
            time.sleep(2)
            #print os.path.getsize(file_name)
        self.parent.time_count = -1
        self.parent.current_song.status = 'playing'

        card = int(self.output_device)
        rate = 1
        tt = -1
        #dm= muxer.Demuxer( str.split( name, '.' )[ -1 ].lower() )
        dm = muxer.Demuxer('mp3')
        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(self.file_name, 'rb')
        self.snd = resampler = dec = None
        s = f.read(32000)
        t = 0
        while (len(s)):
            #print self.local_play_status
            frames = dm.parse(s)
            if frames:
                for fr in frames:
                    # Assume for now only audio streams

                    if dec == None:
                        #print dm.getHeaderInfo(), dm.streams
                        dec = acodec.Decoder(dm.streams[fr[0]])

                    r = dec.decode(fr[1])
                    if r and r.data:
                        if self.snd == None:
                            #print 'Opening sound with %d channels -> %s' % ( r.channels, snds[ card ][ 'name' ] )
                            self.snd = sound.Output(int(r.sample_rate * rate),
                                                    r.channels,
                                                    sound.AFMT_S16_LE, card)
                            #print r.channels
                            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:
                            self.snd.play(data)
                        #print snd.getPosition()
            if tt > 0:
                if self.snd and self.snd.getPosition() < tt:
                    break

            s = f.read(512)
            if self.local_play_status == False:
                break

        while self.snd.isPlaying():
            time.sleep(0.05)
Esempio n. 8
0
    def run(self):
        """ plays a god-damn song """
        
        #local mp3 playback 
        print self.file_name.encode('utf-8')
        self.parent.current_song.status = 'loading'
        while os.path.isfile(self.file_name) != True:
            time.sleep(1)
            
        get_buffer = options.GetSetting('buffer-size-bytes', self.parent.FILEDB)
        if get_buffer != False:
            buffer_sz = int(get_buffer)
        else:
            buffer_sz = BUFFER_SIZE
        while os.path.getsize(self.file_name) < buffer_sz:
            time.sleep(2)
            #print os.path.getsize(file_name)
        self.parent.time_count = -1
        self.parent.current_song.status = 'playing'
            
        
        card = int(self.output_device)
        rate=1
        tt=-1    
        #dm= muxer.Demuxer( str.split( name, '.' )[ -1 ].lower() )
        dm= muxer.Demuxer( 'mp3' )
        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( self.file_name, 'rb' )
        self.snd= resampler= dec= None
        s= f.read( 32000 )
        t= 0
        while (len( s )):
            #print self.local_play_status
            frames= dm.parse( s )
            if frames:
                for fr in frames:
                # Assume for now only audio streams
    
                    if dec== None:
                        #print dm.getHeaderInfo(), dm.streams
                        dec= acodec.Decoder( dm.streams[ fr[ 0 ] ] )
            
                    r= dec.decode( fr[ 1 ] )
                    if r and r.data:
                        if self.snd== None:
                            #print 'Opening sound with %d channels -> %s' % ( r.channels, snds[ card ][ 'name' ] )
                            self.snd= sound.Output( int( r.sample_rate* rate ), r.channels, sound.AFMT_S16_LE, card )
                            #print r.channels
                            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:
                            self.snd.play( data )
                        #print snd.getPosition()
            if tt> 0:
                if self.snd and self.snd.getPosition()< tt:
                    break

            s= f.read( 512 )
            if self.local_play_status == False:               
                break
                    
        while self.snd.isPlaying():
            time.sleep( 0.05 )
def read_radio_stream(url_):

    database = sio.loadmat('mfcc_16_fft256_GMM.mat')
    database.pop('__header__')
    database.pop('__version__')
    database.pop('__globals__')

    r2 = urllib.urlopen(url_)
    pygame.mixer.init(44100, -16, 2, 2048)
    print pygame.mixer.get_init()
    chan1 = pygame.mixer.find_channel()

    format = sound.AFMT_S16_LE
    print sound.getODevices()
    #snd_out = sound.Output(44100, 2, format)

    dm = muxer.Demuxer('mp3')
    dec = None
    snd = None

    print(r2.info())
    print('###################\n')

    #f = open('radio.mp3', 'wb')
    #g = open('radio.wav', 'wb')
    i = 0
    while True:  #i < 3:

        samples = r2.read(15000)

        frames = dm.parse(samples)

        if dec is None:
            # Open decoder
            dec = acodec.Decoder(dm.streams[0])
        

        #start = time.time()
        sound_np_array = ansic_to_numpy(frames, dec)
        #print (sound_np_array.shape[0])/44100.0
        #elapsed = (time.time() - start)
        #print 'decode and ndaray - %2.8f' %elapsed
        
        #start = time.time()
        to_play = np.array(np.repeat(sound_np_array[:, np.newaxis], 2, 1), dtype = 'int16')
        sounds = pygame.sndarray.make_sound(to_play)
        chan1.queue(sounds)
        #elapsed = (time.time() - start)
        #print 'to play - %2.8f' %elapsed

        #start = time.time()
        sound_np_array = decimate(sound_np_array, 4)
        #elapsed = (time.time() - start)
        #print 'downsample - %2.8f' %elapsed

        #start = time.time()
        mfcc_features = MFCC.extract(sound_np_array) #1.5s
        mfcc_features = mfcc_features[:, 1:]
        #elapsed = (time.time() - start)
        #print 'mfcc - %2.8f' %elapsed


        g = mixture.GMM(n_components=16)
        log_prob = -10000
        winner = 'nobody'

        for key, values in database.iteritems():
            try:
                g.means_ = values[0, :, :]
                g.covars_ = values[1, :, :]
                g.weights_ = values[2, :, 1]
                
                #start = time.time()
                temp_prob = np.mean(g.score(mfcc_features))
                #elapsed = (time.time() - start)
                #print 'log-likelihood - %2.8f' %elapsed
                
                if temp_prob > log_prob:
                    log_prob = temp_prob
                    winner = key
            except TypeError:
                print 'error dla ', key

        print winner, log_prob

    print('\n###################')