Exemplo n.º 1
0
    def openDev(self):
        try:
            from __main__ import app
        except:
            app = None
        if app is not None:
            device = app.getPref('audio_device')
        else:
            device = None
        if device is not None:
            log.msg("ossaudiodev opening device %s")
            dev = ossaudiodev.open(device, 'rw')
        else:
            log.msg("ossaudiodev opening default device")
            dev = ossaudiodev.open('rw')
        dev.speed(8000)
        dev.nonblock()
        ch = dev.channels(1)
        if ch not in (1, 2):
            raise ValueError("insane channel count %r"%(ch))
        self._channels = ch
        formats = listFormats(dev)
        if 'AFMT_S16_LE' in formats:
            dev.setfmt(ossaudiodev.AFMT_S16_LE)
            self.dev = dev
        else:
            raise ValueError("Couldn't find signed 16 bit PCM, got %s"%(
                                                    ", ".join(formats)))

        self.LC = LoopingCall(self._push_up_some_data)
        self.LC.start(0.010)
Exemplo n.º 2
0
    def openDev(self):
        try:
            from __main__ import app
        except:
            app = None
        if app is not None:
            device = app.getPref('audio_device')
        else:
            device = None
        if device is not None:
            log.msg("ossaudiodev opening device %s")
            dev = ossaudiodev.open(device, 'rw')
        else:
            log.msg("ossaudiodev opening default device")
            dev = ossaudiodev.open('rw')
        dev.speed(8000)
        dev.nonblock()
        ch = dev.channels(1)
        if ch not in (1, 2):
            raise ValueError("insane channel count %r" % (ch))
        self._channels = ch
        formats = listFormats(dev)
        if 'AFMT_S16_LE' in formats:
            dev.setfmt(ossaudiodev.AFMT_S16_LE)
            self.dev = dev
        else:
            raise ValueError("Couldn't find signed 16 bit PCM, got %s" %
                             (", ".join(formats)))

        self.LC = LoopingCall(self._push_up_some_data)
        self.LC.start(0.010)
Exemplo n.º 3
0
    def available(cls):
        """returns True if OSS output is available on the system"""

        try:
            import ossaudiodev
            ossaudiodev.open("w").close()
            return True
        except (ImportError, IOError):
            return False
Exemplo n.º 4
0
    def available(cls):
        """returns True if OSS output is available on the system"""

        try:
            import ossaudiodev
            ossaudiodev.open("w").close()
            return True
        except (ImportError, IOError):
            return False
Exemplo n.º 5
0
	def setupDDV(self, device = "/dev/ttyu0", port = "9600/8/N/1", timeout = 60.):
		if self.DEBUG_MODE:
			self.log.info("Running...")
		
		
		# These need to be changed first
		self.BACKEND = "DDV"
		self.PROTOCOL_FOOTER = "*DDVF*"
		self.PROTOCOL_HEADER = "*DDVH*"
		
		self.setupRS232(device, port, timeout)
		
		
		# Fudge some settings for improved performance
		self.DATA_LENGTH = 16384
		self.MAX_RETRIES = 1
		self.TX_HANGTIME = 0.
		self.TX_WAIT = 0.
		
		
		# Ensure we can get access to the soundcard, otherwise disable DDV mode
		self.ddv_enabled = False
		
		try:
			import ossaudiodev
			
			
			if self.DEBUG_MODE:
				self.log.info("Setting up DSP device \"%s\" for recording..." % self.DDV_DSP_RECORD_DEVICE)
			
			self.ddv_dsp_record = ossaudiodev.open(self.DDV_DSP_RECORD_DEVICE, "r")
			self.ddv_dsp_record.setfmt(ossaudiodev.AFMT_S16_LE)
			self.ddv_dsp_record.channels(self.DDV_AUDIO_CHANNELS)
			self.ddv_dsp_record.speed(self.DDV_AUDIO_SAMPLERATE)
			
			
			if self.DEBUG_MODE:
				self.log.info("Setting up DSP device \"%s\" for playback..." % self.DDV_DSP_PLAY_DEVICE)
			
			self.ddv_dsp_play = ossaudiodev.open(self.DDV_DSP_PLAY_DEVICE, "w")
			self.ddv_dsp_play.setfmt(ossaudiodev.AFMT_S16_LE)
			self.ddv_dsp_play.channels(self.DDV_AUDIO_CHANNELS)
			self.ddv_dsp_play.speed(self.DDV_AUDIO_SAMPLERATE)
			
			
			self.ddv_enabled = True
			self.log.info("OSS module imported and configured successfully.")
			
		except Exception, ex:
			self.ddv_enabled = False
			
			self.log.fatal(str(ex))
			self.log.info("Unable to import and configure the OSS module, DDV will be disabled.")
Exemplo n.º 6
0
 def initialize(self, mode):
     if not self.fake:
         self.dev = ossaudiodev.open(self.deviceName, mode)
         self.dev.setparameters(self.format,
                                self.number_of_channels,
                                self.sample_rate)
     self.status = mode
Exemplo n.º 7
0
def play_sound_file(data, rate, ssize, nchannels):
    try:
        dsp = ossaudiodev.open('w')
    except IOError, msg:
        if msg[0] in (errno.EACCES, errno.ENODEV, errno.EBUSY):
            raise TestSkipped, msg
        raise TestFailed, msg
Exemplo n.º 8
0
    def init(self, sample_rate, channels, channel_mask, bits_per_sample):
        """initializes the output stream

        this *must* be called prior to play() and close()"""

        if (not self.initialized):
            import ossaudiodev

            self.sample_rate = sample_rate
            self.channels = channels
            self.channel_mask = channel_mask
            self.bits_per_sample = bits_per_sample

            self.ossaudio = ossaudiodev.open('w')
            if (self.bits_per_sample == 8):
                self.ossaudio.setfmt(ossaudiodev.AFMT_S8_LE)
            elif (self.bits_per_sample == 16):
                self.ossaudio.setfmt(ossaudiodev.AFMT_S16_LE)
            elif (self.bits_per_sample == 24):
                self.ossaudio.setfmt(ossaudiodev.AFMT_S16_LE)
            else:
                raise ValueError("Unsupported bits-per-sample")

            self.ossaudio.channels(channels)
            self.ossaudio.speed(sample_rate)

            self.initialized = True
        else:
            self.close()
            self.init(sample_rate=sample_rate,
                      channels=channels,
                      channel_mask=channel_mask,
                      bits_per_sample=bits_per_sample)
Exemplo n.º 9
0
def play_sound_file(data, rate, ssize, nchannels):
    try:
        dsp = ossaudiodev.open('w')
    except IOError, msg:
        if msg[0] in (errno.EACCES, errno.ENOENT, errno.ENODEV, errno.EBUSY):
            raise TestSkipped, msg
        raise TestFailed, msg
Exemplo n.º 10
0
def play(filename):
    logging.info('opening file %s', filename)
    sound_file = wave.open(filename, 'rb')

    try:
        logging.debug('getting parameters')
        (nc, sw, fr, nf, comptype, compname) = sound_file.getparams()
        logging.debug('parameters were %s',
                      (nc, sw, fr, nf, comptype, compname))

        logging.debug('opening audio')
        sound = ossaudiodev.open('w')
        try:
            logging.debug('setting parameters')
            sound.setparameters(ossaudiodev.AFMT_S16_NE, nc, fr)

            logging.debug('read/write loop')
            data = sound_file.readframes(FRAME_SIZE)
            while data:
                sound.write(data)
                data = sound_file.readframes(FRAME_SIZE)

        finally:
            logging.debug('closing sound device')
            sound.close()

    finally:
        logging.debug('closing file')
        sound_file.close()
Exemplo n.º 11
0
def play(filename):
    """ play a .wav file for Windows, Linux, or Mac
        for Mac, you need to have the "play"
        application in the current folder (.)
    """
    if type(filename) != type(''):
        raise(TypeError, 'filename must be a string')
    if os.name == 'nt':
        winsound.PlaySound(filename, winsound.SND_FILENAME)
    elif os.uname()[0] == 'Linux':
        (params, frames) = get_data(filename)
        oss = ossaudiodev.open('w')
        if wave.big_endian:
            if params[1] == 1:
                oss.setfmt(ossaudiodev.AFMT_S8_BE)
            else:
                oss.setfmt(ossaudiodev.AFMT_S16_BE)
        else:
            if params[1] == 1:
                oss.setfmt(ossaudiodev.AFMT_S8_LE)
            else:
                oss.setfmt(ossaudiodev.AFMT_S16_LE)
        oss.channels(params[0])
        oss.speed(params[2])
        oss.writeall(frames)
        oss.close()
    # assume MAC, if not a Windows or Linux machine
    # if you're using another OS, you'll need to adjust this...
    else:
        os.system(('./play ' + filename))
Exemplo n.º 12
0
	def open_audio(self):
		if self.impl:
			self.close_audio()
		self.impl = ossaudiodev.open("/dev/dsp", "w")
		self.impl.setparameters(ossaudiodev.AFMT_S16_LE, 1, self.sampling_rate)
		self.impl.nonblock()
		self.playing = False
Exemplo n.º 13
0
def _ossplay(wav):
    """ Play a sound with OSS, for FreeBSD & OpenBSD """

    try:
        import ossaudiodev
    except ImportError:
        logging.info("_ossplay: Unable to load ossaudiodev module")
        return False

    (nc, sw, fr, nf, comptype, compname) = wav.getparams()

    try:
        dev = ossaudiodev.open('/dev/dsp', 'w')
    except IOError:
        logging.info("_ossplay: Unable to open /dev/dsp; `{}'".format(
            (sys.exc_info()[1])))
        return False

    try:
        from ossaudiodev import AFMT_S16_NE
    except ImportError:
        if byteorder == 'little': AFMT_S16_NE = ossaudiodev.AFMT_S16_LE
        else: AFMT_S16_NE = ossaudiodev.AFMT_S16_BE

    try:
        dev.setparameters(AFMT_S16_NE, nc, fr)
        data = wav.readframes(nf)
        s.close()
        dev.write(data)
    finally:
        dev.close()
Exemplo n.º 14
0
    def play_sound(self, soundfile):
        import ossaudiodev
        import sndhdr

        try:
            (t, r, c, f, b) = sndhdr.what(soundfile)
        except Exception as e:
            print(f"Unable to determine sound header of {soundfile}: {e}")
            return

        if t != "wav":
            print(f"Unable to play non-wav file {soundfile}")
            return

        if b != 16:
            print(f"Unable to support strange non-16-bit audio ({b})")
            return

        dev = None
        try:
            dev = ossaudiodev.open("w")
            dev.setfmt(ossaudiodev.AFMT_S16_LE)
            dev.channels(c)
            dev.speed(r)

            f = file(soundfile, "rb")
            dev.write(f.read())
            f.close()

            dev.close()
        except Exception as e:
            print(f"Error playing sound {soundfile}: {e}")

        if dev:
            dev.close()
Exemplo n.º 15
0
def play(data):
    """
    Play the given audio samples.
    
    @param data: audio samples
    @type data: string of bytes of audio samples
    """
    if not PLAY_ENABLED:
        print(
            "sorry, currently we don't support audio playback on this platform:",
            sys.platform,
            file=sys.stderr)
        return

    try:
        dsp = ossaudiodev.open('w')
    except IOError as e:
        print(
            "can't acquire the audio device; please activate your audio device.",
            file=sys.stderr)
        print("system error message:", str(e), file=sys.stderr)
        return

    dsp.setfmt(ossaudiodev.AFMT_S16_LE)
    dsp.channels(1)
    dsp.speed(16000)
    dsp.write(data)
    dsp.close()
Exemplo n.º 16
0
def _playsoundNix(sound, block = True):
    '''
    Utilizes ossaudiodev. Untested. Probably works with all version of Linux
    with Python 2.3 or newer.

    Inspired by, and more or less copied from, Bill Dandreta's post on
    this mailing list (since deleted, so I link to a web archive instead):
    https://web.archive.org/web/20080218155209/http://mail.python.org/pipermail/python-list/2004-October/288905.html
    '''
    import ossaudiodev
    from sys  import byteorder
    from wave import open as waveOpen, AFMT_S16_LE, AFMT_S16_BE
    
    with waveOpen(sound, 'rb') as sound:
        channelCount, sampleWidth, framerate, frameCount, compressionType, compressionName = sound.getparams()
        try:
            from ossaudiodev import AFMT_S16_NE
        except ImportError:
            if 'little' in byteorder.lower():
                AFMT_S16_NE = ossaudiodev.AFMT_S16_LE
            else:
                AFMT_S16_NE = ossaudiodev.AFMT_S16_BE
        data = sound.readframes(frameCount)

    speaker = ossaudiodev.open('/dev/dsp', 'w')
    speaker.setparameters(AFMT_S16_NE, channelCount, framerate)
    speaker.write(data)
    speaker.close()
Exemplo n.º 17
0
    def __init__(self, fname, time_interval=None, lag=0.):
        """
        Initialize class.
        """
        threading.Thread.__init__(self)

        if not time_interval:
            time_interval = 0.05

        self.time_interval = time_interval

        self.lock = threading.Lock()
        self.is_running = False

        self._timestamp = None

        b, e = os.path.splitext(fname)
        #if not (e == '.mp3' or e == '.m4a'):
        #    fname = b + '.mp3'

        fname = os.path.normpath(fname)

        if not os.path.isfile(fname):
            raise IOError('Input file does not exist: %s' % fname)

        print('Load audio data: %s' % os.path.basename(fname))
        b, e = os.path.splitext(fname)
        fname_wav = b + '.wav'
        data_audio, sample_rate = read_wav(fname_wav)

        num_frames, num_channels = data_audio.shape

        self.fname = fname
        self.data_audio = data_audio

        self.num_frames = num_frames
        self.num_channels = num_channels
        self.sample_rate = sample_rate

        print('Load audio analysis')
        self.audio_beats, self.audio_segments = analyze_song(fname)

        print('Configure audio device')
        self.chunk_size = int(self.time_interval * self.sample_rate)
        print('  time interval: %.1f ms' % (self.time_interval*1000))
        print('  audio chunk size: %d' % self.chunk_size)

        self.audio_device = ossaudiodev.open('w')
        self.audio_device.setparameters(ossaudiodev.AFMT_S16_LE, self.num_channels, self.sample_rate)

        bufsize =  self.audio_device.bufsize()
        self.bufsize = bufsize
        print('  audio buffer size: %d' % bufsize)

        time.sleep(0.01)
        self.audio_device.setparameters(ossaudiodev.AFMT_S16_LE, self.num_channels, self.sample_rate)

        # Estimate time lag.
        self.lag = float(bufsize)/self.chunk_size * self.time_interval + lag
        print('  time lag: %.3f' % self.lag)
Exemplo n.º 18
0
def play(filename):
  logging.info('opening file %s', filename)
  sound_file = wave.open(filename,'rb')

  try:
    logging.debug('getting parameters')
    (nc, sw, fr, nf, comptype, compname) = sound_file.getparams()
    logging.debug('parameters were %s', (nc, sw, fr, nf, comptype, compname))

    logging.debug('opening audio')
    sound = ossaudiodev.open('w')
    try:
      logging.debug('setting parameters')
      sound.setparameters(ossaudiodev.AFMT_S16_NE, nc, fr)

      logging.debug('read/write loop')
      data = sound_file.readframes(FRAME_SIZE)
      while data:
        sound.write(data)
        data = sound_file.readframes(FRAME_SIZE)

    finally:
      logging.debug('closing sound device')
      sound.close()

  finally:
    logging.debug('closing file')
    sound_file.close()
Exemplo n.º 19
0
def get_swipe(dev='/dev/audio'):
    audio = ossaudiodev.open(dev, 'r')
    audio.setparameters(ossaudiodev.AFMT_S16_LE, 1, 44100)
    
    baselines = deque([2**15] * 4)
    bias = 0
    while 1:
        data, power = get_chunk(audio, bias)
        
        baseline = sum(baselines) / len(baselines) * THRESHOLD_FACTOR
        print power, baseline, power / (baseline or 1)
        
        chunks = []
        while power > baseline:
            print power, baseline, power / (baseline or 1), '*'
            chunks.append(data)
            data, power = get_chunk(audio, bias)

        if len(chunks) > 1:
            data = old_data + ''.join(chunks) + data
            while audioop.maxpp(data[:3000], 2) < baseline / 2:
                data = data[1000:]
            while audioop.maxpp(data[-3000:], 2) < baseline / 2:
                data = data[:-1000]
            
            return audioop.bias(data, 2, -audioop.avg(data, 2))

        old_data = data
        
        bias = -audioop.avg(data, 2)
        
        baselines.popleft()
        baselines.append(power)
Exemplo n.º 20
0
def sampleaudio(filename, seconds=2.0, devname="/dev/dsp", samplerate=44100, byteorder="little"):
	dev = audio.open(devname, 'r')

	try:
		from ossaudiodev import AFMT_S16_NE
	except:
		if byteorder == "big":
			AFMT_S16_NE = audio.AFMT_S16_BE
		else:
			AFMT_S16_NE = audio.AFMT_S16_LE
	
	fmt = dev.setfmt(AFMT_S16_NE)
	channels = dev.channels(1)
	rate = dev.speed(samplerate)

	timearray = []
	timearray.append(time.time() * 1000.0)
	bytestring = dev.read(int(seconds*rate*2))
	timearray.append(time.time() * 1000.0)
	timearray.append(rate/1000.0)

	dev.close()

	data = np.fromstring(bytestring, dtype=np.int16)
	np.savetxt(filename, data)

	return np.array(timearray, dtype=np.float)
Exemplo n.º 21
0
def _playsoundNix(sound, block=True):
    '''
    Utilizes ossaudiodev. Untested. Probably works with all version of Linux
    with Python 2.3 or newer.

    Inspired by, and more or less copied from, Bill Dandreta's post on
    this mailing list (since deleted, so I link to a web archive instead):
    https://web.archive.org/web/20080218155209/http://mail.python.org/pipermail/python-list/2004-October/288905.html
    '''
    import ossaudiodev
    from sys import byteorder
    from wave import open as waveOpen, AFMT_S16_LE, AFMT_S16_BE

    with waveOpen(sound, 'rb') as sound:
        channelCount, sampleWidth, framerate, frameCount, compressionType, compressionName = sound.getparams(
        )
        try:
            from ossaudiodev import AFMT_S16_NE
        except ImportError:
            if 'little' in byteorder.lower():
                AFMT_S16_NE = ossaudiodev.AFMT_S16_LE
            else:
                AFMT_S16_NE = ossaudiodev.AFMT_S16_BE
        data = sound.readframes(frameCount)

    speaker = ossaudiodev.open('/dev/dsp', 'w')
    speaker.setparameters(AFMT_S16_NE, channelCount, framerate)
    speaker.write(data)
    speaker.close()
Exemplo n.º 22
0
def get_swipe(dev='/dev/audio'):
    audio = ossaudiodev.open(dev, 'r')
    audio.setparameters(ossaudiodev.AFMT_S16_LE, 1, 44100)

    baselines = deque([2**15] * 4)
    bias = 0
    while 1:
        data, power = get_chunk(audio, bias)

        baseline = sum(baselines) / len(baselines) * THRESHOLD_FACTOR
        print power, baseline, power / (baseline or 1)

        chunks = []
        while power > baseline:
            print power, baseline, power / (baseline or 1), '*'
            chunks.append(data)
            data, power = get_chunk(audio, bias)

        if len(chunks) > 1:
            data = old_data + ''.join(chunks) + data
            while audioop.maxpp(data[:3000], 2) < baseline / 2:
                data = data[1000:]
            while audioop.maxpp(data[-3000:], 2) < baseline / 2:
                data = data[:-1000]

            return audioop.bias(data, 2, -audioop.avg(data, 2))

        old_data = data

        bias = -audioop.avg(data, 2)

        baselines.popleft()
        baselines.append(power)
Exemplo n.º 23
0
 def __init__(self):
     out = ossaudiodev.open('w')
     out.channels(1)
     out.setfmt(ossaudiodev.AFMT_S16_LE)
     out.speed(44100)
     self.channel = out
     self._play = out.writeall
Exemplo n.º 24
0
    def __init__(self, OSSIETalk_ref):
        '''Initialization.  Sets a reference to parent.  
        Initializes the buffer.  Starts the Process data
        thread, which waits for data to be added to the buffer'''

        self.OSSIETalk_ref = OSSIETalk_ref

        # new method:
        self.num_channels = audio_channels
        self.Fs = audio_sampling_frequency
        try:
            self.speaker_driver = ossaudiodev.open('w')
        except IOError:
            print "[WorkModules] Failed to open playback device for writing"
        self.speaker_driver.setfmt(ossaudiodev.AFMT_S16_LE)
        self.speaker_driver.channels(self.num_channels)
        self.speaker_driver.speed(self.Fs)

        self.data_queue = []
        self.data_queue_lock = threading.Lock()
        self.data_signal = threading.Event()

        self.is_running = True

        # old method:
        #self.channels = 2
        #self._setup_sound()

        self.my_decoder = cvsd.decoder()

        self.process_thread = threading.Thread(target=self.Process)
        self.process_thread.start()
Exemplo n.º 25
0
 def __init__(self):
     out = ossaudiodev.open('w')
     out.channels(1)
     out.setfmt(ossaudiodev.AFMT_S16_LE)
     out.speed(44100)
     self.channel = out
     self._play = out.writeall
Exemplo n.º 26
0
def test_main():
    try:
        dsp = ossaudiodev.open('w')
    except (ossaudiodev.error, IOError), msg:
        if msg[0] in (errno.EACCES, errno.ENOENT, errno.ENODEV, errno.EBUSY):
            raise TestSkipped(msg)
        raise
Exemplo n.º 27
0
	def __init__(self):
		if sys.platform == 'linux2':
			import ossaudiodev
			self.stream = ossaudiodev.open('w')
			self.stream.setparameters(ossaudiodev.AFMT_S16_LE, 2, 44100)
		else:
			self.p = pyaudio.PyAudio()
			self.stream = self.p.open(format=self.p.get_format_from_width(2), channels=2, rate=44100, output=True)
Exemplo n.º 28
0
 def play_sound_file(self, data, rate, ssize, nchannels):
     try:
         dsp = ossaudiodev.open('w')
     except IOError, msg:
         if msg.args[0] in (errno.EACCES, errno.ENOENT, errno.ENODEV,
                            errno.EBUSY):
             raise TestSkipped(msg)
         raise
Exemplo n.º 29
0
def getdev():
    import ossaudiodev
    dev = ossaudiodev.open('rw')
    dev.speed(8000)
    #dev.nonblock()
    ch = dev.channels(1)
    dev.setfmt(ossaudiodev.AFMT_S16_LE)
    return dev
Exemplo n.º 30
0
def getdev():
    import ossaudiodev
    dev = ossaudiodev.open('rw')
    dev.speed(8000)
    #dev.nonblock()
    ch = dev.channels(1)
    dev.setfmt(ossaudiodev.AFMT_S16_LE)
    return dev
Exemplo n.º 31
0
 def __init__(self, device, rate):
     self.ossdevice = ossaudiodev.open(device, "w")
     if sys.byteorder == 'little':
         self.ossdevice.setfmt(ossaudiodev.AFMT_S16_LE)
     else:
         self.ossdevice.setfmt(ossaudiodev.AFMT_S16_BE)
     self.ossdevice.channels(2)
     self.ossdevice.speed(rate)
Exemplo n.º 32
0
 def __init__(self, device, rate):
     self.ossdevice = ossaudiodev.open(device, "w")
     if sys.byteorder == 'little':
         self.ossdevice.setfmt(ossaudiodev.AFMT_S16_LE)
     else:
         self.ossdevice.setfmt(ossaudiodev.AFMT_S16_BE)
     self.ossdevice.channels(2)
     self.ossdevice.speed(rate)
Exemplo n.º 33
0
 def __init__(self):
     self.audio = ossaudiodev.open('rw')
     self.audio.setfmt(format)
     self.audio.channels(2)
     self.speed = self.audio.speed(speed)
     self.data = ''
     self.buffer = array.array('B')
     self.index = 0
Exemplo n.º 34
0
 def __init__(self, state):
     self.output = ossaudiodev.open('w')
     self.Clip = None
     self.file = None
     self.state = state
     state.addObserver(self)
     self.isPlaying = False
     self.src = None
     self.t = None
Exemplo n.º 35
0
def playwave(wavefile):
    fo = wave.open(wavefile, "rb")
    (nc, sw, fr, nf, comptype, compname) = fo.getparams()
    dsp = ossaudiodev.open("/dev/dsp", "w")
    dsp.setparameters(ossaudiodev.AFMT_S16_NE, nc, fr)
    data = fo.readframes(nf)
    fo.close()
    dsp.write(data)
    dsp.close()
Exemplo n.º 36
0
 def oss_open(self):
     import ossaudiodev
     self.oss = ossaudiodev.open("/dev/dsp" + str(self.card) + ".0", "r")
     self.oss.setfmt(ossaudiodev.AFMT_S16_LE)
     self.oss.channels(2)
     assert self.oss.speed(self.rate) == self.rate
     self.th = threading.Thread(target=lambda: self.oss_thread())
     self.th.daemon = True
     self.th.start()
Exemplo n.º 37
0
 def oss_open(self):
     import ossaudiodev
     self.oss = ossaudiodev.open("/dev/dsp" + str(self.card) + ".0", "r")
     self.oss.setfmt(ossaudiodev.AFMT_S16_LE)
     self.oss.channels(2)
     assert self.oss.speed(self.rate) == self.rate
     self.th = threading.Thread(target=lambda : self.oss_thread())
     self.th.daemon = True
     self.th.start()
Exemplo n.º 38
0
    def play_audio(self, voice, text):
        reply = self.request("synth", voice, text)
        if reply["sampletype"] != "int16":
            raise Exception("Client currently only supports 16bit samplesize")

        # try using pyaudio
        try:
            import pyaudio

            chunk = 1024
            start = 0
            end = 1024

            p = pyaudio.PyAudio()

            # note: currently supports only 'int16' sample types (i.e. samplewidth = 2)
            samplewidth = 2

            # open stream
            stream = p.open(
                format=p.get_format_from_width(samplewidth), channels=1, rate=reply["samplerate"], output=True
            )

            num_samples = len(reply["samples"]) / 2
            while end < num_samples:
                stream.write(reply["samples"][start:end])
                start = end
                end = end + chunk

            stream.write(reply["samples"][start:])
            stream.stop_stream()
            stream.close()
            p.terminate()

        # no pyaudio
        except ImportError:
            import os

            opsys = os.name

            if opsys not in ("posix", "nt"):
                raise EnvironmentError(
                    "TTSClient.play_audio() currently works only on" + ' "posix" and "nt" compatible systems'
                )

            if opsys == "posix":
                import ossaudiodev

                dsp = ossaudiodev.open("w")
                dsp.setparameters(ossaudiodev.AFMT_S16_LE, 1, reply["samplerate"], True)
                dsp.writeall(reply["samples"])
                dsp.close()

            else:  # nt (win)
                import winsound

                winsound.PlaySound(reply["samples"], winsound.SND_MEMORY)
Exemplo n.º 39
0
    def play_audio(self, voice, text):
        reply = self.request("synth", voice, text)
        if reply["sampletype"] != "int16":
            raise Exception("Client currently only supports 16bit samplesize")

        # try using pyaudio
        try:
            import pyaudio
            chunk = 1024
            start = 0
            end = 1024

            p = pyaudio.PyAudio()

            # note: currently supports only 'int16' sample types (i.e. samplewidth = 2)
            samplewidth = 2

            # open stream
            stream = p.open(format=p.get_format_from_width(samplewidth),
                            channels=1,
                            rate=reply["samplerate"],
                            output=True)

            num_samples = len(reply["samples"]) / 2
            while (end < num_samples):
                stream.write(reply["samples"][start:end])
                start = end
                end = end + chunk

            stream.write(reply["samples"][start:])
            stream.stop_stream()
            stream.close()
            p.terminate()

        #no pyaudio
        except ImportError:
            import os

            opsys = os.name

            if opsys not in ("posix", "nt"):
                raise EnvironmentError("TTSClient.play_audio() currently works only on" + \
                                       " \"posix\" and \"nt\" compatible systems")

            if opsys == "posix":
                import ossaudiodev

                dsp = ossaudiodev.open("w")
                dsp.setparameters(ossaudiodev.AFMT_S16_LE, 1,
                                  reply["samplerate"], True)
                dsp.writeall(reply["samples"])
                dsp.close()

            else:  # nt (win)
                import winsound
                winsound.PlaySound(reply["samples"], winsound.SND_MEMORY)
Exemplo n.º 40
0
def test_main():
    try:
        dsp = ossaudiodev.open('w')
    except (ossaudiodev.error, IOError) as msg:
        if msg.args[0] in (errno.EACCES, errno.ENOENT,
                           errno.ENODEV, errno.EBUSY):
            raise TestSkipped(msg)
        raise
    dsp.close()
    support.run_unittest(__name__)
Exemplo n.º 41
0
def get_oss_audio_device(dev="/dev/audio"):
    """Get the ossaudiodev."""
    try:
        import ossaudiodev

        audio = ossaudiodev.open(dev, "r")
        audio.setparameters(ossaudiodev.AFMT_S16_LE, 1, 44100)
        return audio
    except Exception:
        raise DecodeError("Failed to open OSS audio device.")
    def test_set_parameters(self):
        dsp = ossaudiodev.open("w")
        try:
            self.set_parameters(dsp)

            # Disabled because it fails under Linux 2.6 with ALSA's OSS
            # emulation layer.
            #self.set_bad_parameters(dsp)
        finally:
            dsp.close()
            self.failUnless(dsp.closed)
Exemplo n.º 43
0
    def test_set_parameters(self):
        dsp = ossaudiodev.open("w")
        try:
            self.set_parameters(dsp)

            # Disabled because it fails under Linux 2.6 with ALSA's OSS
            # emulation layer.
            #self.set_bad_parameters(dsp)
        finally:
            dsp.close()
            self.failUnless(dsp.closed)
Exemplo n.º 44
0
	def open(self):
		#Try to open device in read-write mode
		try:
			self.device = dev.open('rw')
			self.device.setparameters(dev.AFMT_S16_LE, CHANNELS, SAMPLE_RATE) 
			self.device.nonblock()
			self.isopen = True
  
		except IOError:
			print "Couldn't open device..."
			self.isopen = False
		return self.isopen
Exemplo n.º 45
0
    def __init__(self):
        if sys.platform == 'linux2':
            # make sure you've started this with $ padsp python infinite_playlist [...]
            import ossaudiodev

            self.stream = ossaudiodev.open('w')
            self.stream.setparameters(ossaudiodev.AFMT_S16_LE, 2, 44100)
        else:
            import pyaudio

            self.p = pyaudio.PyAudio()
            self.stream = self.p.open(format=self.p.get_format_from_width(2), channels=2, rate=44100, output=True)
Exemplo n.º 46
0
 def music_delivery(self, session, frames, frame_size, num_frames,
         sample_type, sample_rate, channels):
     if num_frames == 0:
         if self._device is not None:
             self._device.close()
             self._device = None
         return 0
     if self._device is None:
         self._device = ossaudiodev.open('w')
         self._device.setparameters(self._format, channels, sample_rate)
     self._device.write(frames)
     return num_frames
Exemplo n.º 47
0
 def music_delivery(self, session, frames, frame_size, num_frames,
                    sample_type, sample_rate, channels):
     if num_frames == 0:
         if self._device is not None:
             self._device.close()
             self._device = None
         return 0
     if self._device is None:
         self._device = ossaudiodev.open('w')
         self._device.setparameters(self._format, channels, sample_rate)
     self._device.write(frames)
     return num_frames
Exemplo n.º 48
0
            def close(self):
                # Yeah, we have to make it crossplatform
                if sys.platform == "win32":
                    import winsound
                    winsound.PlaySound(self.audio, winsound.SND_MEMORY)
                elif sys.platform.startswith("linux"):

                    def f(n):
                        return ord(n) if isinstance(n, str) else n

                    sample_rate = 0
                    sample_rate |= f(self.audio[24])
                    sample_rate |= f(self.audio[25]) << 8
                    sample_rate |= f(self.audio[26]) << 16
                    sample_rate |= f(self.audio[27]) << 24
                    raw = self.audio[44:]

                    try:
                        os.stat("/dev/dsp")
                        # Worked, using OSS
                        import ossaudiodev
                        with ossaudiodev.open("w") as audio:
                            audio.setfmt(ossaudiodev.AFMT_U8)
                            audio.channels(1)
                            audio.speed(sample_rate)
                            audio.write(raw)
                    except IOError:
                        # Didn't work, using PulseAudio
                        import ctypes
                        import struct

                        class Spec(ctypes.Structure):
                            _fields_ = (("format", ctypes.c_int),
                                        ("rate", ctypes.c_uint32),
                                        ("channels", ctypes.c_uint8))

                        spec = Spec(0, sample_rate, 1)
                        pa = ctypes.cdll.LoadLibrary("libpulse-simple.so.0")
                        s = pa.pa_simple_new(None, "PDPy11", 1, None, "PDPy11",
                                             ctypes.byref(spec), None, None,
                                             None)
                        pa.pa_simple_write(s, raw, len(raw), None)
                        pa.pa_simple_drain(s)
                        pa.pa_simple_free(s)
                elif sys.platform == "darwin":
                    import subprocess
                    import tempfile
                    path = tempfile.mktemp()
                    with open(path, "w") as f:
                        f.write(self.audio)
                    subprocess.Popen(["afplay", "-q", "1", path]).wait()
                    os.unlink(path)
Exemplo n.º 49
0
 def __init__(self,rate=44100,channels=2,fps=30):
      try:
        self.ao=oss.open_audio()
      except:
        self.ao=oss.open('w')
      if (hasattr(self.ao,'stereo')):
        self.ao.stereo(1)
      self.ao.speed(rate)
      if (hasattr(self.ao,'format')):
        self.ao.format(oss.AFMT_S16_LE)
      else:
        self.ao.setfmt(oss.AFMT_S16_LE)
      self.ao.channels(channels)
Exemplo n.º 50
0
 def doPlayOss(self):
     dev = ossaudiodev.open(self.device, "w")
     fdtuple = self.handle.loadFile()
     dev.setfmt(ossaudiodev.AFMT_S16_LE)
     dev.channels(2)
     dev.speed(fdtuple[0][1])
     while self.shouldPlay:
         buf = fdtuple[1].read()
         if buf is None or self.shouldNext:
             break
         dev.write(buf)
     dev.close()
     return self.shouldPlay
Exemplo n.º 51
0
def test():
    (data, rate, ssize, nchannels) = read_sound_file(findfile('audiotest.au'))
    play_sound_file(data, rate, ssize, nchannels)

    dsp = ossaudiodev.open("w")
    try:
        test_setparameters(dsp)

        # Disabled because it fails under Linux 2.6 with ALSA's OSS
        # emulation layer.
        #test_bad_setparameters(dsp)
    finally:
        dsp.close()
Exemplo n.º 52
0
def print_fmts(rw):
    print(rw == "r" and "read" or "write")
    sound = ossaudiodev.open(rw)
    fmts = sound.getfmts()

    for name in dir(ossaudiodev):
        if name.startswith("AFMT"):
            attr = getattr(ossaudiodev, name)
            if attr & fmts:
                print(name)

    print()
    sound.close()
Exemplo n.º 53
0
def print_fmts(rw):
    print(rw == 'r' and 'read' or 'write')
    sound = ossaudiodev.open(rw)
    fmts = sound.getfmts()

    for name in dir(ossaudiodev):
        if name.startswith('AFMT'):
            attr = getattr(ossaudiodev, name)
            if attr & fmts:
                print(name)

    print()
    sound.close()
Exemplo n.º 54
0
def test():
    (data, rate, ssize, nchannels) = read_sound_file(findfile('audiotest.au'))
    play_sound_file(data, rate, ssize, nchannels)

    dsp = ossaudiodev.open("w")
    try:
        test_setparameters(dsp)

        # Disabled because it fails under Linux 2.6 with ALSA's OSS
        # emulation layer.
        #test_bad_setparameters(dsp)
    finally:
        dsp.close()
Exemplo n.º 55
0
 def __init__(self, audio_file):
     self.af = audio_file
     self.wf = wave.open(self.get_wav(), 'rb')
     if sys.platform == 'linux2':
         # make sure you've started this with $ padsp python infinite_playlist [...]
         import ossaudiodev
         self.stream = ossaudiodev.open('w')
         self.stream.setparameters(ossaudiodev.AFMT_S16_LE, self.af.numChannels, self.af.sampleRate)
     else:
         import pyaudio
         p = pyaudio.PyAudio()
         self.stream = p.open(format=p.get_format_from_width(self.wf.getsampwidth()),
                              channels=self.af.numChannels, rate=self.af.sampleRate, output=True)
Exemplo n.º 56
0
    def set_format(self, sample_rate, channels, channel_mask, bits_per_sample):
        """sets the output stream to the given format

        if the stream hasn't been initialized, this method initializes it

        if the stream has been initialized to a different format,
        this method closes and reopens the stream to the new format

        if the stream has been initialized to the same format,
        this method does nothing"""

        if (self.__ossaudio__ is None):
            # output hasn't been initialized

            import ossaudiodev

            AudioOutput.set_format(self, sample_rate, channels, channel_mask,
                                   bits_per_sample)

            # initialize audio output device and setup framelist converter
            self.__ossaudio__ = ossaudiodev.open('w')
            self.__ossmixer__ = ossaudiodev.openmixer()
            if (self.bits_per_sample == 8):
                self.__ossaudio__.setfmt(ossaudiodev.AFMT_S8_LE)
                self.__converter__ = lambda f: f.to_bytes(False, True)
            elif (self.bits_per_sample == 16):
                self.__ossaudio__.setfmt(ossaudiodev.AFMT_S16_LE)
                self.__converter__ = lambda f: f.to_bytes(False, True)
            elif (self.bits_per_sample == 24):
                from audiotools.pcm import from_list

                self.__ossaudio__.setfmt(ossaudiodev.AFMT_S16_LE)
                self.__converter__ = lambda f: from_list([
                    i >> 8 for i in list(f)
                ], self.channels, 16, True).to_bytes(False, True)
            else:
                raise ValueError("Unsupported bits-per-sample")

            self.__ossaudio__.channels(channels)
            self.__ossaudio__.speed(sample_rate)
        elif (not self.compatible(sample_rate=sample_rate,
                                  channels=channels,
                                  channel_mask=channel_mask,
                                  bits_per_sample=bits_per_sample)):
            # output has been initialized to a different format

            self.close()
            self.set_format(sample_rate=sample_rate,
                            channels=channels,
                            channel_mask=channel_mask,
                            bits_per_sample=bits_per_sample)
Exemplo n.º 57
0
def play_sound(sfile, dur=None):
    """play the first <dur> seconds of the specified wav file"""
    sf = wave.open(sfile, 'rb')
    ad = ossaudiodev.open('w')
    fmt = [ossaudiodev.AFMT_S8, ossaudiodev.AFMT_S16_LE][sf.getsampwidth() - 1]
    sr = sf.getframerate()
    ad.setparameters(fmt, sf.getnchannels(), sr)
    if dur is None:
        nframes = sf.getnframes()
    else:
        nframes = int(dur * sr)
    ad.write(sf.readframes(nframes))
    sf.close()
    ad.close()
Exemplo n.º 58
0
 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)