Exemplo n.º 1
0
 def __init__(self):
     """x.__init__(...) initializes x; see x.__class__.__doc__ for signature"""
     super(AOAudioPlaybackAdaptor, self).__init__()
     try:
         self.dev = ao.AudioDevice("oss")
     except ao.aoError:
         self.dev = ao.AudioDevice("alsa")
Exemplo n.º 2
0
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))
Exemplo n.º 3
0
    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))
Exemplo n.º 4
0
	def listen(self,
			   start = 0,
			   length = 0,
			   dsp = "/dev/dsp"):


		device = ao.AudioDevice("oss",
								bits = 16,
								rate = self.framerate,
								channels = self.channels)
		wave_object = self._get_wave()

		startframe = int(start * self.framerate)
		if length == 0:
			length = self.number_of_frames -  startframe
		else:
			length = int(length * self.framerate)
		wave_object.setpos(startframe)

		print "start, length:", start, length
		print startframe, length
		
		frames = wave_object.readframes(length)

		try:
			device.play(frames)
		except KeyboardInterrupt:
			pass
		del device
Exemplo n.º 5
0
def getSignature(filename, playWhileReading=None):
    (path, ext) = os.path.splitext(filename)
    if ext.lower() == '.ogg':
        ff = ogg.vorbis.VorbisFile(filename)
    elif ext.lower() == '.mp3':
        ff = MadWrapper(filename)
    elif ext.lower() == '.wav':
        ff = WavWrapper(filename)
    else:
        raise SystemError, "Unsupported audio file."

    if playWhileReading:
        device = 'esd'
        id = ao.driver_id(device)
        aodev = ao.AudioDevice(id)

    info = ff.info()
    trm = musicbrainz.trm()
    trm.SetPCMDataInfo(info.rate, info.channels, 16)
    while 1:
        (buff, bytes, bit) = ff.read()
        if bytes == 0:
            break
        if trm.GenerateSignature(buff):
            break
        if playWhileReading:
            aodev.play(buff, bytes)

    sig = trm.FinalizeSignature()

    return sig
Exemplo n.º 6
0
def main():
    if len(sys.argv) < 3:
        print('Usage: %s <server name/ip> <server port>' % sys.argv[0])
        sys.exit(1)

    wrap = mywrapper()
    cond_filled = threading.Condition()

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((sys.argv[1], int(sys.argv[2])))

    recv_thread = threading.Thread(target=recv_thread_func,
                                   args=(wrap, cond_filled, sock))
    recv_thread.daemon = True
    recv_thread.start()

    dev = ao.AudioDevice('pulse')
    play_thread = threading.Thread(target=play_thread_func,
                                   args=(wrap, cond_filled, dev))
    play_thread.daemon = True
    play_thread.start()

    PROTOCOL_bytes = bytes('MRTSP', encoding='utf-8')

    while True:
        line = input('>> ')
        one_arg = False
        if ' ' in line:
            cmd, args = line.split(' ', 1)
        else:
            cmd = line
            one_arg = True

        if cmd in ['l', 'list']:
            print('The user asked for list.')
            LIST_bytes = bytes(METHODS[0], encoding='utf-8')
            send_data = struct.pack('5s4sI', PROTOCOL_bytes, LIST_bytes, 0)
            sock.send(send_data)
        if cmd in ['p', 'play']:
            if one_arg == False:  # input does have sid
                print('The user asked to play:', args)
                sid = int(args)
                PLAY_bytes = bytes(METHODS[1], encoding='utf-8')
                send_data = struct.pack('5s4sI', PROTOCOL_bytes, PLAY_bytes,
                                        sid)
                sock.send(send_data)
        if cmd in ['s', 'stop']:
            print('The user asked for stop.')
            STOP_bytes = bytes(METHODS[2], encoding='utf-8')
            send_data = struct.pack('5s4sI', PROTOCOL_bytes, STOP_bytes, 0)
            sock.send(send_data)
        if cmd in ['quit', 'q', 'exit']:
            if wrap.method == 'PLAY':
                # NOTE: don't worry, the server will not keep sending after
                # the song ended! check server.py:203
                print('Please stop your song before leaving!')
                continue
            sys.exit(0)

    sock.close()
Exemplo n.º 7
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')
Exemplo n.º 8
0
 def __init__(self, id=None):
     import ao
     if id is None:
         id = ao.driver_id('alsa')  # oss
     self.dev = ao.AudioDevice(
         id, channels=1
     )  # rate, AudioDevice(aodevice, bits=16,rate=44100, byte_format=4,channels=1)
Exemplo n.º 9
0
def main():
    if len(sys.argv) < 3:
        print 'Usage: %s <server name/ip> <server port>' % sys.argv[0]
        sys.exit(1)

    # Create a pseudo-file wrapper, condition variable, and socket.  These will
    # be passed to the thread we're about to create.
    wrap = mywrapper()

    # Create a condition variable to synchronize the receiver and player threads.
    # In python, this implicitly creates a mutex lock too.
    # See: https://docs.python.org/2/library/threading.html#condition-objects
    cond_filled = threading.Condition()

    # Create a TCP socket and try connecting to the server.
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((sys.argv[1], int(sys.argv[2])))

    # Create a thread whose job is to receive messages from the server.
    recv_thread = threading.Thread(
        target=recv_thread_func,
        args=(wrap, cond_filled, sock)
    )
    recv_thread.daemon = True
    recv_thread.start()

    # Create a thread whose job is to play audio file data.
    dev = ao.AudioDevice('pulse')
    play_thread = threading.Thread(
        target=play_thread_func,
        args=(wrap, cond_filled, dev)
    )
    play_thread.daemon = True
    play_thread.start()

    # Enter our never-ending user I/O loop.  Because we imported the readline
    # module above, raw_input gives us nice shell-like behavior (up-arrow to
    # go backwards, etc.).
    while True:
        line = raw_input('>> ')

        if ' ' in line:
            cmd, args = line.split(' ', 1)
        else:
            cmd = line

        # TODO: Send messages to the server when the user types things.
        if cmd in ['l', 'list']:
            print 'The user asked for list.'

        if cmd in ['p', 'play']:
            print 'The user asked to play:', args

        if cmd in ['s', 'stop']:
            print 'The user asked for stop.'

        if cmd in ['quit', 'q', 'exit']:
            sys.exit(0)
Exemplo n.º 10
0
 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()
Exemplo n.º 11
0
Arquivo: test.py Projeto: del82/pymad
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))
Exemplo n.º 12
0
def play(f):  # f: Filename
    if not path.exists(f):
        ui.throw('文件不存在:' + f)
        return
    mf = mad.MadFile(f)
    dev = ao.AudioDevice('alsa', rate=mf.samplerate())
    ui.setInfo(f, mf.total_time())
    ui.g.lrcFile = lrc.changeExt(f)
    if not lrc.loadLrc(ui.g.lrcFile):  # No LRC file
        ui.g.lrcFile = ''
    g.skip = False
    while not g.skip:
        if not g.paused:
            buf = mf.read()
            if buf is None:
                break
            dev.play(buf, len(buf))
            ui.setTime(mf.current_time())
        else:
            time.sleep(0.1)
        ui.draw()
Exemplo n.º 13
0
def madradio(url):
    scheme, netloc, path, params, query, fragment = urlparse(url)
    try:
        host, port = netloc.split(':')
    except ValueError:
        host, port = netloc, 80
    if not path:
        path = '/'
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((host, int(port)))
    sock.send('GET %s HTTP/1.0\r\n\r\n' % path)
    reply = sock.recv(1500)
    # print repr(reply)
    file = sock.makefile()
    mf = mad.MadFile(file)
    print(('bitrate %lu bps' % mf.bitrate()))
    print(('samplerate %d Hz' % mf.samplerate()))
    dev = ao.AudioDevice(0, rate=mf.samplerate())
    while True:
        buffy = mf.read()
        if buffy is None:
            break
        dev.play(buffy, len(buffy))
def main():
    # Open the audio device.
    dev = ao.AudioDevice('pulse')

    # 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')

    while True:

        # data = f.read(5000)
        # data = "MEOW|100|>^,^<|" + data + "|>^,^<|>^,^<"
        # data_len = len(data)
        # print("LEN: {}".format(data_len))
        # data = struct.pack("5300s", data)
        # data = struct.unpack("5300s", data)[0]
        # tokens = data.split("|")
        # tokens = tokens[3: len(tokens) - 2]
        # data = "|".join(tokens)

        # 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
                print("BUF IS NONE")
                break
            dev.play(buffer(buf), len(buf))
Exemplo n.º 15
0
# -*- coding: utf-8 -*-
# kate: space-indent on; indent-width 4; replace-tabs on;

from __future__ import division

import sys
import ffmpeg
import ao

pcm = ao.AudioDevice("pulse")

rdr = ffmpeg.Decoder(sys.argv[-1])

from numpy import array, log10, sqrt
import struct
from scipy import fft
import audioop


from OpenGL import GL, GLUT

class OglRenderer( object ):
    def __init__( self, source, duration, width=250, height=100 ):
        self.source   = source
        self.duration = duration
        self.width    = width
        self.height   = height

        self.points = []

        GLUT.glutInit( sys.argv )
Exemplo n.º 16
0
  def update(self):
    if self.stream is None:
        self.p = pyaudio.PyAudio()
        if len(self.audioSrc) > 5:
          self.mf = mad.MadFile(self.audioSrc)
          self.sampleRate = self.mf.samplerate()
          self.stream = self.p.open(format = pyaudio.paInt32, channels = 2, rate = self.sampleRate, output = True)
          self.dev = ao.AudioDevice('pulse', rate = self.sampleRate)
          threading.Thread(target=self.getmp3stream).start()
        else:
          for x in range(self.p.get_device_count()):
            if self.p.get_device_info_by_index(x)['name'] == audioSrc:
              break;
          if x < self.p.get_device_count()-1:
            self.stream = self.p.open(format = pyaudio.paInt16, channels = 1, rate = self.sampleRate, input = True, frames_per_buffer = self.bufferSize*2, input_device_index = x)
          else:
            raise Exception("Could not find pulse audio device")
          threading.Thread(target=self.getstream).start()

    if len(self.chunks) > 0:
      d = np.fromstring(self.chunks.pop(0), dtype=np.short)
      ffty = np.fft.fft(d)
      ffty = abs(ffty[0:len(ffty)*0.5])*0.0001
      ffty1 = ffty[:len(ffty)*0.5]
      ffty2 = ffty[len(ffty)*0.5::]+2
      ffty2 = ffty2[::-1]
      ffty = ffty1+ffty2
      ffty = np.log(ffty)-2
      #fftx,ffty = self.downSample(self.fftx,ffty,5)
      ffty = self.smoothMemory(ffty,3)
      if len(ffty) > 0: self.data = ffty[1:int(len(ffty)*self.split)] * self.factor
      
    if len(self.data) > 0:
      #print str(len(ffty))+' samples, '+str((min(ffty)+1)*0.5)+' -> '+str((max(ffty)+1)*0.5)
      count = 0.0

      glBegin(GL_TRIANGLES)
      glColor4f(1.0, 1.0, 1.0, 0.6)

      for i in self.data:
        val = np.array([(count/len(self.data), (count+1)/len(self.data)), (0.0, i)]) * self.winSize
        glVertex3f(val[0][0], val[1][0], 0.0)
        glVertex3f(val[0][1], val[1][0], 0.0)
        glVertex3f(val[0][1], val[1][1], 0.0)
      
        glVertex3f(val[0][1], val[1][1], 0.0)
        glVertex3f(val[0][0], val[1][1], 0.0)
        glVertex3f(val[0][0], val[1][0], 0.0)
        count += 1.0
      glEnd()

      click = self.mouse.checkClick()
      select = self.mouse.checkSelect()
      
      for s in self.selections:
        s.update(self.data)
      if self.mouse.checkClick() == 0: self.MOUSE = True # Check for a new click
      if self.MOUSE == True:
        selection = self.mouse.getSelection() # Get current selection if mouse has registered a click
        if self.mouse.MOUSE == False: # If the mouse has been released
          self.MOUSE = False # Set local variable
          self.selections.append(selection) # Add selection to array if the mouse has been released
      
      ss = self.selections # Make a copy of the selections
      if self.MOUSE == True: ss.prepend(selection) # Prepend the current selection to the temp selections list 
      
      for s in ss:

        if self.mouse.MOUSE == True:
          average = 0.2
        else:
          average = np.average(self.data[int(s[0][0]*len(self.data)):int(s[1][0]*len(self.data))])
          average = (average - s[0][1]) / (s[1][1] - s[0][1])
          if average > 1.0: average = 1.0
          if average < 0.0: average = 0.0
      
        s = s * np.array([self.mouse.winSize, self.mouse.winSize]) + [(1,1),(0,0)]
         
        glBegin(GL_TRIANGLES)
        
        glColor4f(1.0,1.0,1.0,average)
        
        glVertex3f(s[0][0], s[0][1], 0.0)
        glVertex3f(s[1][0], s[0][1], 0.0)
        glVertex3f(s[1][0], s[1][1], 0.0)
        
        glVertex3f(s[1][0], s[1][1], 0.0)
        glVertex3f(s[0][0], s[1][1], 0.0)
        glVertex3f(s[0][0], s[0][1], 0.0)
        
        glEnd()

        glBegin(GL_LINES)
        
        glColor4f(1.0,1.0,1.0,1.0)
        
        glVertex3f(s[0][0], s[0][1], 0.0)
        glVertex3f(s[1][0], s[0][1], 0.0)

        glVertex3f(s[1][0], s[0][1], 0.0)
        glVertex3f(s[1][0], s[1][1], 0.0)
        
        glVertex3f(s[1][0], s[1][1], 0.0)
        glVertex3f(s[0][0], s[1][1], 0.0)

        glVertex3f(s[0][0], s[1][1], 0.0)
        glVertex3f(s[0][0], s[0][1], 0.0)
        
        glEnd()
Exemplo n.º 17
0
def main():
    if len(sys.argv) < 3:
        print 'Usage: %s <server name/ip> <server port>' % sys.argv[0]
        sys.exit(1)
    wrap = mywrapper()

   
    cond_filled = threading.Condition()


    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((sys.argv[1], int(sys.argv[2])))


    recv_thread = threading.Thread(
        target=recv_thread_func,
        args=(wrap, cond_filled, sock)
    )
    recv_thread.daemon = True
    recv_thread.start()
    
    dev = ao.AudioDevice('pulse')
    play_thread = threading.Thread(
        target=play_thread_func,
        args=(wrap, cond_filled, dev)
    )
    play_thread.daemon = True
    play_thread.start()

  
    while True:
        line = raw_input('>> ')

        if ' ' in line:
            cmd, args = line.split(' ', 1)
        else:
            cmd = line

        message = ""

       
        if cmd in ['l', 'list']:
            message = "REQUEST\nclient-ip: {}\n request-type: list\n\n\r\n".format(sock.getsockname()[0])

        if cmd in ['p', 'play']:
            message = "REQUEST\nclient-ip: {}\nrequest-type: play\nsong-number: {}\n\n\r\n".format(sock.getsockname()[0], args)
            print 'The user asked to play:', args
            wrap.state = 1

        if cmd in ['s', 'stop']:
            message = "REQUEST\nclient-ip: {}\n request-type: stop\n\n\r\n".format(sock.getsockname()[0])
            print 'The user asked for stop.'
            wrap.data = ""
            wrap.mf = None
            wrap.state = 0

        if cmd in ['quit', 'q', 'exit']:
            sock.close()
            sys.exit(0)

        sock.send(message)

    sock.close()
Exemplo n.º 18
0
	def __init__(self, filename):
		id = ao.driver_id('alsa')
		self.vf = ogg.vorbis.VorbisFile(filename)
		self.device = ao.AudioDevice(id)
Exemplo n.º 19
0
#!/usr/bin/env python

'''short.py - a really brief demonstration of using the ao and hip modules'''

import hip
import ao
import sys

filename = sys.argv[1]
device = 'esd'
SIZE = 4806

hf = hip.hip(filename)
id = ao.driver_id(device)
ao = ao.AudioDevice(id)

while 1:
    (buff, bytes, bit) = hf.read(SIZE)
    if bytes == 0: break
    ao.play(buff, bytes)
Exemplo n.º 20
0
 def __init__(self, id=None):
     super(AOPlayerComponent, self).__init__()
     #if id is None:
     #   id = 'oss'
     #print "FOO1"
     self.dev = ao.AudioDevice("oss")
Exemplo n.º 21
0
#!/usr/bin/python

# Very simple FLAC player using the FLAC FileDecoder and libao

import flac.decoder as decoder
import flac.metadata as metadata
import ao
import sys

# setup libao audio device
#ao = ao.AudioDevice('esd')
#ao = ao.AudioDevice('alsa09')
#ao = ao.AudioDevice('wav', filename='out.wav')
ao = ao.AudioDevice('oss')


# write our callbacks (in Python!!)
def metadata_callback(dec, block):
    if block.type == metadata.VORBIS_COMMENT:
        # use flac.metadata to access vorbis comments!
        vc = metadata.VorbisComment(block)
        print vc.vendor_string
        for k in vc.comments:
            print '%s=%s' % (k, vc.comments[k])


def error_callback(dec, status):
    pass


def write_callback(dec, buff, size):
Exemplo n.º 22
0
"""The player_madao module provides the Player class.

This implementation of Player uses python wrappers for libmad and libao,
which provide interfaces to audio files and audio devices.
"""
import thread
import time
import ao
import mad

AODEV = ao.AudioDevice(0)


class Player(object):
    """The Player class provides an audio stream for a file."""
    _filename = None
    _madfile = None
    _is_playing = False  # may need a lock since stop and play_internal both write
    _callback = None

    def __init__(self, filename):
        """Construct a Player.

        :param filename
        """
        self._filename = filename
        self.reset()

    def length(self):
        """Get the length of the audio stream in milliseconds."""
        return self._madfile.total_time()
Exemplo n.º 23
0
def main():
    '''
    main function
    '''

    if len(sys.argv) < 3:
        print('Usage: {} <server name/ip> <server port>'.format(sys.argv[0]))
        sys.exit(1)

    # Create a pseudo-file wrapper.
    wrap = mywrapper()

    global BOOL_PLAY  #pylint: disable=global-statement

    # Create a condition variable to synchronize the receiver and
    # player threads. This implicitly creates a mutex lock too.
    cond_filled = threading.Condition()

    # Create a TCP socket and try connecting to the server.
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((sys.argv[1], int(sys.argv[2])))

    # Create a thread whose job is to receive messages from the server,
    # using the socket, condition variable, and psuedo-file wrapper.
    recv_thread = threading.Thread(target=recv_thread_func,
                                   args=(wrap, cond_filled, sock))

    recv_thread.daemon = True
    recv_thread.start()

    # set up audio device
    dev = ao.AudioDevice('pulse')

    # set up play thread
    play_thread = threading.Thread(target=play_thread_func,
                                   args=(wrap, cond_filled, dev))

    # start play thread
    play_thread.daemon = True
    play_thread.start()

    # Enter our never-ending user I/O loop.
    # Because we imported the readline module above, raw_input gives us
    # nice shell-like behavior (up-arrow to go backwards, etc.).
    while True:
        line = raw_input('>> ')  #pylint: disable=undefined-variable

        if ' ' in line:
            cmd, args = line.split(' ', 1)
        else:
            cmd = line

        if cmd in ['l', 'list']:
            print('The user asked for a list of all songs available.')

            # send request to server to list all available songs
            send_request('list', sock)

        elif cmd in ['p', 'play']:
            if ' ' not in line:
                print("Please type in a song ID to play")
                continue
            print('The user asked to play:', args)

            BOOL_PLAY = False
            # if already playing, stop and clear buffer
            send_request('stop', sock)
            stop(wrap, cond_filled)
            sleep(2)
            BOOL_PLAY = True
            # send request to server to play
            send_request('play', sock, line)

        elif cmd in ['s', 'stop']:
            print('The user asked to stop.')
            BOOL_PLAY = False

            # send request to server to stop sending packets
            send_request('stop', sock)

            # clear wrapper
            stop(wrap, cond_filled)

        elif cmd in ['quit', 'q', 'exit']:
            print('The user asked to exit.')
            sys.exit(0)

        else:
            print('Incorrect usage; please try again.')
Exemplo n.º 24
0
def main():
    if len(sys.argv) < 3:
        print 'Usage: %s <server name/ip> <server port>' % sys.argv[0]
        sys.exit(1)

    # Create a pseudo-file wrapper, condition variable, and socket.  These will
    # be passed to the thread we're about to create.
    wrap = mywrapper()

    global curr_song
    global curr_play

    # Create a condition variable to synchronize the receiver and player threads.
    # In python, this implicitly creates a mutex lock too.
    # See: https://docs.python.org/2/library/threading.html#condition-objects
    cond_filled = threading.Condition()

    # Create a TCP socket and try connecting to the server.
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((sys.argv[1], int(sys.argv[2])))

    # Create a thread whose job is to receive messages from the server.
    recv_thread = threading.Thread(target=recv_thread_func,
                                   args=(wrap, cond_filled, sock))
    recv_thread.daemon = True
    recv_thread.start()

    # Create a thread whose job is to play audio file data.
    dev = ao.AudioDevice('pulse')
    play_thread = threading.Thread(target=play_thread_func,
                                   args=(wrap, cond_filled, dev))
    play_thread.daemon = True
    play_thread.start()

    # Enter our never-ending user I/O loop.  Because we imported the readline
    # module above, raw_input gives us nice shell-like behavior (up-arrow to
    # go backwards, etc.).
    while True:
        line = raw_input('>> ')

        if ' ' in line:
            cmd, args = line.split(' ', 1)
        else:
            cmd, args = line, None

        if cmd in ['l', 'list']:
            print 'The user asked for list.'
            p = Packet(msg_type='list')
            send_packet(p, sock, 'list')

        elif cmd in ['p', 'play']:
            if args == None or unicode(args).isnumeric() == False:
                print 'Please enter a song ID number to play'
                continue
            print 'The user asked to play:', args

            # stop playing the current song before playing a new song
            curr_song = None
            curr_play = False
            p = Packet(msg_type='stop')
            send_packet(p, sock, 'stop')
            stop_play(wrap, cond_filled)
            sleep(1)

            # now send play packet
            curr_song = args
            curr_play = True
            p = Packet(msg_type='play', song_id=args)
            send_packet(p, sock, 'play')

        elif cmd in ['s', 'stop']:
            print 'The user asked to stop.'
            curr_song = None
            curr_play = False
            p = Packet(msg_type='stop')
            send_packet(p, sock, 'stop')
            stop_play(wrap, cond_filled)

        elif cmd in ['quit', 'q', 'exit']:
            print 'The user asked to quit.'
            p = Packet(msg_type='quit')
            send_packet(p, sock, 'quit')
            sys.exit(0)

        else:
            print 'Please input a valid command'
Exemplo n.º 25
0
def play_array(a, sr):
    data = a.tostring()
    dev = ao.AudioDevice(0, bits=16, channels=1, rate=sr)
    print dev.driver_info(), sr
    dev.play(data)
Exemplo n.º 26
0
def main():
    if len(sys.argv) < 4:
        print 'Usage: %s <download directory> <server name/ip> <server port>' % sys.argv[
            0]
        sys.exit(1)

    #get the download path from client to store downloaded songs
    download_dir = str(sys.argv[1])

    # Create a pseudo-file wrapper, condition variable, and socket.  These will
    # be passed to the thread we're about to create.
    wrap = mywrapper()
    wrap.mf = mad.MadFile(wrap)

    # Create a condition variable to synchronize the receiver and player threads.
    # In python, this implicitly creates a mutex lock too.
    # See: https://docs.python.org/2/library/threading.html#condition-objects
    cond_filled = threading.Condition()

    # Create a TCP socket and try connecting to the server.
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((sys.argv[2], int(sys.argv[3])))

    # Create a thread whose job is to receive messages from the server.
    recv_thread = threading.Thread(target=recv_thread_func,
                                   args=(wrap, cond_filled, sock,
                                         download_dir))
    recv_thread.daemon = True
    recv_thread.start()

    # Create a thread whose job is to play audio file data.
    dev = ao.AudioDevice('pulse')
    play_thread = threading.Thread(target=play_thread_func,
                                   args=(wrap, cond_filled, dev))
    play_thread.daemon = True
    play_thread.start()

    # Enter our never-ending user I/O loop.  Because we imported the readline
    # module above, raw_input gives us nice shell-like behavior (up-arrow to
    # go backwards, etc.).
    while True:
        line = raw_input('>> ')

        if ' ' in line:
            cmd, args = line.split(' ', 1)
        else:
            cmd = line

        # TODO: Send messages to the server when the user types things.
        if cmd in ['l', 'list']:
            print 'The user asked for list.'
            sendRequest(sock, cmd)

        elif cmd in ['p', 'play']:
            if ' ' not in line:
                print "Enter song id or song name!"
                continue

            print 'The user asked to play:', args

            #wrap.mp = None
            #if the music is already downloaded locally
            '''
            if args in downloaded:
                f = open(download_dir+"/"+downloaded[args], '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
            '''

            if playing[0]:
                playing[0] = False
                cond_filled.acquire()

                wrap.data = ''
                wrap.mf = mad.MadFile(wrap)
                cond_filled.notify()
                cond_filled.release()

                sendRequest(sock, "stop")

            sendRequest(sock, cmd + " " + args)

        elif cmd in ['s', 'stop']:
            if not playing[0]:
                print "No song is playing!"
                continue
            playing[0] = False
            print 'The user asked for stop.'
            cond_filled.acquire()

            wrap.data = ''
            wrap.mf = mad.MadFile(wrap)
            cond_filled.notify()
            cond_filled.release()

            sendRequest(sock, cmd)

        elif cmd in ['quit', 'q', 'exit']:
            sendRequest(sock, cmd)
            sock.close()
            sys.exit(0)
        else:
            print "Try again, wrong command"
Exemplo n.º 27
0
    def playAudio(self, audio_data, tp='mplayer_mp3'):
        if tp == 'mplayer_mp3':
            cmd = 'mplayer -novideo -nolirc -cache 1024 -really-quiet -softvol -volume 100 -'
            cmd = shlex.split(cmd)
            #-#            debug('EXEC_CMD< %s ...', cmd)
            proc = subprocess.Popen(cmd, stdin=subprocess.PIPE)
            try:
                outs, errs = proc.communicate(audio_data, timeout=30)
                proc.kill()  # TODO useless ?
                outs, errs = proc.communicate()
                proc.terminate()
            except subprocess.TimeoutExpired:
                warn('kill timeout proc %s', proc)
                proc.kill()
                outs, errs = proc.communicate()
        elif tp == 'play':
            #-#            cmd = 'play -t mp3 - -q gain -b -l 10'
            cmd = 'play -t mp3 - -q'
            cmd = shlex.split(cmd)
            #-#            debug('EXEC_CMD< %s ...', cmd)
            proc = None
            try:
                proc = subprocess.Popen(cmd, stdin=subprocess.PIPE)
                outs, errs = proc.communicate(audio_data, timeout=30)
            except subprocess.TimeoutExpired:
                if proc:
                    warn('kill timeout proc %s', proc)
                    proc.kill()
                    outs, errs = proc.communicate()
        elif tp == 'mplayer':
            cmd = 'mplayer -demuxer rawaudio -rawaudio channels=1:rate=16000:bitrate=16  -novideo -really-quiet -noconsolecontrols -nolirc -'
            cmd = shlex.split(cmd)
            debug('EXEC_CMD< %s ...', cmd)
            proc = subprocess.Popen(cmd, stdin=subprocess.PIPE)
            try:
                outs, errs = proc.communicate(audio_data, timeout=30)
            except subprocess.TimeoutExpired:
                warn('kill timeout proc %s', proc)
                proc.kill()
                outs, errs = proc.communicate()
        elif tp == 'ao':
            import ao
            ao.AudioDevice('raw', bits=16, rate=16000,
                           channels=1).play(audio_data)
        elif tp == 'pcm':
            import alsaaudio
            pcm = alsaaudio.PCM(card='Intel')
            pcm.setchannels(2)
            pcm.setrate(16000)
            pcm.setformat(alsaaudio.PCM_FORMAT_S16_LE)
            # play pcm file from tts
            pcm.write(audio_data)
            del pcm
        if tp == 'pyaudio':
            with noalsaerr():
                p = pyaudio.PyAudio()
#-#            stream = p.open(format=p.get_format_from_width(2), channels=2, rate=16000, output=True)
            stream = p.open(format=pyaudio.paInt16,
                            channels=1,
                            rate=16000,
                            output=True)
            stream.write(audio_data)
            sleep(0.5)  # wait steam play done
            stream.stop_stream()
            stream.close()
            p.terminate()
Exemplo n.º 28
0
#!/usr/bin/python
import mad
import ao
import sys

mf = mad.MadFile(sys.argv[1])
dev = ao.AudioDevice('alsa', rate=mf.samplerate())
while 1:
    buf = mf.read()
    if buf is None:
        break
    dev.play(buf, len(buf))
Exemplo n.º 29
0
 def __init__(self, aodevice, rate, options):
     self.ao = ao.AudioDevice(aodevice,
                              rate=rate,
                              byte_format=4,
                              options=options)
Exemplo n.º 30
0
--- cypack/player.py.bak	2011-02-12 21:11:21.000000000 +0100
+++ cypack/player.py	2011-02-12 21:12:19.000000000 +0100
@@ -370,7 +370,7 @@
         import mad, ao
         self.mf = mad.MadFile(self.path)
         self.total = self.mf.total_time()/1000
-        dev = ao.AudioDevice('alsa', rate=self.mf.samplerate())
+        dev = ao.AudioDevice('oss', rate=self.mf.samplerate())
         global player
         while 1:
             # manually halted, set mode to stop - to make sure poll won't