Esempio n. 1
0
    def __init__(self,
                 pitch=0,
                 pitch_per_second=12,
                 decibels=0,
                 decibels_per_second=1,
                 channels=1,
                 channel_side="lr",
                 samplerate=utilities.DEFAULT_SAMPLE_RATE):

        self.sinewave_generator = sinewave_generator.SineWaveGenerator(
            pitch=pitch,
            pitch_per_second=pitch_per_second,
            decibels=decibels,
            decibels_per_second=decibels_per_second,
            samplerate=samplerate)

        # Create the output stream
        self.output_stream = sd.OutputStream(
            channels=channels,
            callback=lambda *args: self._callback(*args),
            samplerate=samplerate)

        self.channels = channels

        if channel_side == 'r':
            self.channel_side = 0
        elif channel_side == 'l':
            self.channel_side = 1
        else:
            self.channel_side = -1
Esempio n. 2
0
    def __init__(self, stationMHz):
        self.sdr = rtlsdr.RtlSdr()
        self.validsGains = self.sdr.get_gains()
        self.indexGain = 10

        self.f_offset = 250000  # Desplazamiento para capturar
        self.f_station = stationMHz  # Frecuencia de radio

        self.dec_rate = int(FS / F_BW)
        self.fs_y = FS / (self.dec_rate)
        self.coef = remez(N_TRAPS, [0, F_BW, F_BW * 1.4, FS / 2], [1, 0],
                          Hz=FS)
        self.expShift = (-1.0j * 2.0 * np.pi * self.f_offset / FS)

        # Se configura los parametros
        self.dec_audio = int(self.fs_y / AUDIO_FREC)
        self.stream = sd.OutputStream(device='default',
                                      samplerate=int(self.fs_y /
                                                     self.dec_audio),
                                      channels=1,
                                      dtype='float32')
        self.beginListening = 0

        self.soundQueue = queue.Queue()
        self.samplesQueue = queue.Queue()
Esempio n. 3
0
    def receive(self, listening_port, number_of_chunks_received):

        if __debug__:
            print(f"receive: listening_port={listening_port}")

        # UDP socket to receive
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        listening_endpoint = ("0.0.0.0", listening_port)
        self.sock.bind(listening_endpoint)

        def callback(outdata, frames, time, status):
            outdata, source_address = self.sock.recvfrom(Intercom.max_packet_size)
            number_of_chunks_received.value += 1

        with sd.OutputStream(
                samplerate=self.samples_per_second,
                blocksize=self.samples_per_chunk,
                device=None,
                channels=self.number_of_channels,
                dtype=numpy.int16,
                callback=callback):

            while True:
                time.sleep(1)
                print("o")
        while True:
            callback(None, None, None, None)
Esempio n. 4
0
def easy_sound(freq, pos, decay, fbins):

    stream = sd.OutputStream(dtype = np.int16, channels=2)
    stream.start()
    time = 0.4
    wave = 0;
    samples = np.arange(44100*1*time)/44100.0
    count = 0
    for i in range(len(fbins)):
        if (fbins[i]*freq > 20000.0):
            break
        count += 1
        cf = fbins[i]*freq
        idf = 0.005
        a = np.sin(np.pi*(i+1)*pos/1.0)/(343*fbins[i]*freq)
        alpha = (1/4)*1*(2-(np.sin(2*np.pi*(i+1))/(np.pi * (i+1))))
        a /= alpha
        print(str(i) + " " + str(a))
        wave += a * np.exp(-decay*cf*idf*samples) * np.sin(2*np.pi*(fbins[i]*freq)*samples)

    count = 1/count
    wave *= count

    # for i in range(len(wave)):
        # print(wave[i])
        # wave[i] *= np.exp(-decay*(i/44100))

    wav_wave = np.array(wave/np.max(np.abs(wave))*32767, dtype=np.int16)
    stream.write(wav_wave)
    stream.close()
    # scipy.io.wavfile.write(str(freq) + '.wav', 44100, wav_wave)
    return wav_wave
    def __init__(self, audioformat, queue=None):
        """Constructor.
		Creates a pyaudio sound renderer.
		
		Parameters
		----------
		audioformat : dict
			A dictionary containing the properties of the audiostream
		queue : Queue.queue
			A queue object which serves as a buffer on which the individual
			audio frames are placed by the decoder.
		"""
        global sd
        import sounddevice as sd

        # Init thread
        super(SoundrendererSounddevice, self).__init__()

        if not queue is None:
            self.queue = queue

        self.stream = sd.OutputStream(
            channels=audioformat["nchannels"],
            samplerate=audioformat["fps"],
            dtype='int{}'.format(audioformat['nbytes'] * 8),
            blocksize=audioformat["buffersize"],
        )
Esempio n. 6
0
    def __init__(self, out_bufferL, out_bufferR, out_i, outlock):

        self.out_bufferL = out_bufferL
        self.out_bufferR = out_bufferR

        self.out_i = out_i
        self.zeros = np.zeros(config.BUFFERSIZE, dtype=np.float32)
        self.outlock = outlock
        sd.default.device = config.DEVICE
        sd.default.samplerate = config.SAMPLERATE
        sd.default.latency = 'low'

        logging.info('>> AUDIO OUTPUTS:\n{}'.format(sd.query_devices()))
        logging.info('>> AUDIO OUTPUT: {}'.format(config.DEVICE))

        self.last_looptime = 0
        self.lastoutbuffer = None
        if config.AUTORECORD:
            self.soundfile = sf.SoundFile('{}.wav'.format(
                datetime.datetime.timestamp(datetime.datetime.now())),
                                          'w',
                                          samplerate=config.SAMPLERATE,
                                          channels=config.NCHANNELS)

        with sd.OutputStream(dtype=config.CAST,
                             channels=config.NCHANNELS,
                             callback=self.callback,
                             blocksize=config.BUFFERSIZE) as self.stream:

            while True:
                time.sleep(config.SLEEPTIME)
def stream_func(device=-1, chunk=256):
    def callback(outdata, frames, time, status):
        try:
            data = next(sound_slice)
            if flags_stream_trem[0] is False:
                raise sd.CallbackStop
            else:
                outdata[:, :] = data
        except ValueError:
            outdata[:, :] = np.zeros((blocksize, 2))

    def gen():
        global sound
        sound = np.zeros((blocksize, 2))
        while True:
            slice = sound[:blocksize, :]
            yield slice
            sound = sound[blocksize:, :]

    blocksize = chunk
    sound_slice = gen()
    device = device if device >= 0 else None
    stream = sd.OutputStream(device=device, channels=2, callback=callback,
                             blocksize=blocksize, samplerate=sample_rate)

    with stream:
        while flags_stream_trem[0] is True:
            time.sleep(0.5)
        else:
            stream.__exit__()
Esempio n. 8
0
    def _process_playback_command(self, cmd):
        phase_offset = 0
        cfg = cmd.config

        # Make the code adaptive to both python 2 and 3
        shared_vars = {"cmd": cmd, "phase_offset": phase_offset}

        def playback_cb(outdata, frames, time, status):
            phase_offset = shared_vars["phase_offset"]
            cmd = shared_vars["cmd"]
            cfg = cmd.config

            signal = np.arange(outdata.shape[0])
            signal = signal * 2 * np.pi / cfg.fs + phase_offset
            phase_offset += outdata.shape[0] * 2 * np.pi / cfg.fs
            signal = 0.99 * np.sin(signal * cmd.out_freq)

            for cidx in range(outdata.shape[1]):
                outdata[:, cidx] = signal

            shared_vars["phase_offset"] = phase_offset
            shared_vars["cmd"] = cmd

        with sd.OutputStream(channels=cfg.ch,
                             callback=playback_cb,
                             samplerate=cfg.fs,
                             dtype="float32"):
            while cmd.is_playing:
                sd.sleep(500)
Esempio n. 9
0
    def _playback(self):
        phase_offset = 0

        # Make the code adaptive to both python 2 and 3
        shared_vars = {"phase_offset": phase_offset, "data": self.data}

        def playback_cb(outdata, frames, time, status):
            phase_offset = shared_vars["phase_offset"]
            data = shared_vars["data"]

            signal = np.arange(outdata.shape[0])
            signal = signal * 2 * np.pi / self.sr + phase_offset
            phase_offset += outdata.shape[0] * 2 * np.pi / self.sr
            signal = 0.99 * np.sin(signal * 440)

            for cidx in range(outdata.shape[1]):
                outdata[:, cidx] = data[cidx]
                #outdata[:, cidx] = signal

            shared_vars["phase_offset"] = phase_offset

        with sd.OutputStream(channels=self.ch,
                             callback=playback_cb,
                             samplerate=self.sr,
                             dtype="float32"):
            while self.is_playing:
                sd.sleep(500)
Esempio n. 10
0
def open_output_stream(device=None, channels=2, samplerate=44100):
    global output_stream
    if sd:
        output_stream = sd.OutputStream(
            dtype='float32'
        )  # device=device, samplerate=samplerate, latency='low', clip_off=True, dither_off=True, never_drop_input=True)
        output_stream.start()
Esempio n. 11
0
    def __init__(self, device_name=None, sample_rate=44100):
        """
        Create a control voltage output device.

        Control voltage signals require a DC-coupled audio interface, which Python
        sends audio signals to via the sounddevice library. 

        Args:
            device_name (str): Name of the audio output device to use.
                               To query possible names, call get_cv_output_devices().
            sample_rate (int): Audio sample rate to use.
        """
        try:
            self.stream = sounddevice.OutputStream(
                device=device_name,
                samplerate=sample_rate,
                dtype="float32",
                callback=self.audio_callback)
            self.stream.start()

        except NameError:
            raise Exception(
                "For CV support, the sounddevice module must be installed")

        # Expert Sleepers ES-8 supports entire -10V to +10V range
        self.output_voltage_max = 10
        self.channels = self.stream.channels
        self.channel_notes = [None] * self.channels
        self.middle_c = 60

        print("Started CV output with %d channels" % self.channels)
Esempio n. 12
0
 def __init__(self,
              mode,
              streamOptions={},
              dataQueue=None,
              rw_autoStop=True,
              stopwatch=StopWatch(error=False)):
     self.mode = mode
     if self.mode == "rw":
         if not "callback" in streamOptions:
             streamOptions.update(callback=self._Queue2)
         self.sdStream = sounddevice.Stream(dtype="float32",
                                            **streamOptions)
         self.rw_autoStop = rw_autoStop
     elif self.mode == "r":
         if not "callback" in streamOptions:
             streamOptions.update(callback=self._Queue)
         self.sdStream = sounddevice.InputStream(dtype="float32",
                                                 **streamOptions)
     elif self.mode == "w":
         if not "callback" in streamOptions:
             streamOptions.update(callback=self._Queue)
         self.sdStream = sounddevice.OutputStream(dtype="float32",
                                                  **streamOptions)
     else:
         raise ModeError("Unknown mode.")
     if dataQueue is None:
         if self.mode == "rw":
             self.dataQueue = (queue.Queue(), queue.Queue())
         else:
             self.dataQueue = queue.Queue()
     else:
         self.dataQueue = dataQueue
     self.state = "stop"
     self.stopwatch = stopwatch
     self.last_frametime = 0
Esempio n. 13
0
def play_only():
    with sd.OutputStream(device=device_name,
                         channels=channels,
                         callback=callback,
                         samplerate=samplerate):
        print("press return to quit")
        input()
Esempio n. 14
0
def audio_sink(sample_seq, fs):
    q = queue.Queue()

    def audio_callback(outdata, frames, time, status):
        if not q.empty():
            outdata[:] = q.get_nowait()

    stream = sounddevice.OutputStream(samplerate=10000,
                                      blocksize=3360,
                                      dtype="float32",
                                      callback=audio_callback,
                                      channels=2)

    # prefill buffer
    for samples in itertools.islice(sample_seq, 4):
        ll, ul = np.min(samples), np.max(samples)
        s = samples * 0.5 / (ul - ll + 1)
        q.put(s.reshape(-1, 1))

    with stream:
        for samples in sample_seq:
            if samples is None:
                break
            ll, ul = np.min(samples), np.max(samples)
            s = samples * 0.5 / (ul - ll + 1)
            q.put(s.reshape(-1, 1))
Esempio n. 15
0
def denoiser_output():
    global LIVE
    device_out = "Soundflower (2ch)"
    caps = query_devices(device_out, "output")
    channels_out = min(caps['max_output_channels'], 1)
    stream_out = sd.OutputStream(device=None,
                                 samplerate=sample_rate,
                                 channels=channels_out)
    stream_out.start()
    while (1):
        while (LIVE == 1):
            if buffer != []:
                while len(buffer) > 10:
                    del (buffer[0])
                frame = buffer[0]
                del (buffer[0])
                # print(len(buffer))
                start = time.time()
                output = omlsa_streamer(frame,
                                        sample_rate,
                                        frame_length,
                                        frame_move,
                                        postprocess="butter",
                                        high_cut=3000)
                print(time.time() - start)
                stream_out.write(output.astype(np.float32))
        while (LIVE == 0):
            if buffer != []:
                while len(buffer) > 10:
                    del (buffer[0])
                frame = buffer[0]
                del (buffer[0])
                stream_out.write(frame)
    stream_out.stop()
Esempio n. 16
0
def main():

    vocal = Voc(sd.default.samplerate)

    def process(outdata, frames, time, status):

        if status:
            print(status)

        _osc = 0
        _voc = 0
        if vocal.counter == 0:
            _osc = 12 + 16 * (0.5 * (_osc + 1))
            vocal.tongue_shape(_osc, 2.9)

        out = np.array(vocal.compute(), dtype=np.float32)[:CHUNK]

        print(outdata.shape, out.shape)

        outdata[:] = out.reshape(-1, 1)


    with sd.OutputStream(channels=1, callback=process, blocksize=CHUNK, samplerate=sd.default.samplerate) as ostream:
        print(ostream.cpu_load)
        sd.sleep(int(duration * 1000))
        print(ostream.cpu_load)
Esempio n. 17
0
 def StartSnd(self,serial_event):
     # open audio thread
     self.sd1 = sd.OutputStream(dtype='float32',callback=callback,blocksize=256)
     self.sd1.start()
     # open serial thread
     self.tser=threading.Thread(target=self.SerialDect,args=(serial_event,),name='serialdetect')
     self.tser.start()
Esempio n. 18
0
    def __init__(self, out_fs, out_channel, out_bit_depth, frames_per_buffer,
                 usb_card_keyword):
        threading.Thread.__init__(self)
        # 初始化配置
        self.daemon = True
        self.exit_flag = False
        self.out_fs = out_fs
        self.out_channels = out_channel
        self.out_bit_depth = out_bit_depth
        self.frames_per_buffer = frames_per_buffer
        params = {
            "samplerate": out_fs,
            "device": None,
            "channels": out_channel,
            "dtype": np.float32,
        }

        # 为当前所有可用输出设备创建输出流
        self.devices = OutputDeviceIterable(usb_card_keyword)
        self.streams = StreamsIterable()
        for index, info in self.devices:
            print(index, info["name"])
            params["device"] = index
            self.streams.append(sd.OutputStream(**params))
        self.start()
Esempio n. 19
0
def play_unbuffered(gen, blocksize=1024, samplerate=44100):
    t = 0

    def callback(outdata, frames, time, status):
        nonlocal t
        nonlocal gen
        if status:
            return
        for i in range(blocksize):
            outdata[i, 0] = gen.amp((t + i) / samplerate)
        t += blocksize

    try:
        stream = sd.OutputStream(samplerate=samplerate,
                                 blocksize=blocksize,
                                 device=sd.default.device,
                                 channels=1,
                                 dtype='float32',
                                 callback=callback)
        with stream:
            threading.Event().wait()
    except KeyboardInterrupt:
        return
    except Exception as e:
        tb.print_exc()
Esempio n. 20
0
 def load(self, sample_rate, dtype, block, channels, callback):
     self.reset()
     self.stream = sd.OutputStream(samplerate=sample_rate,
                                   blocksize=block,
                                   channels=channels,
                                   callback=callback,
                                   dtype=self.get_dtype_string(dtype))
Esempio n. 21
0
    def __init__(self,
                 pitch=0,
                 pitch_per_second=12,
                 decibels=0,
                 decibels_per_second=1,
                 samplerate=utilities.DEFAULT_SAMPLE_RATE,
                 collect_data=False,
                 silent=False):
        self.sinewave_generator = sinewave_generator.SineWaveGenerator(
            pitch=pitch,
            pitch_per_second=pitch_per_second,
            decibels=decibels,
            decibels_per_second=decibels_per_second,
            samplerate=samplerate)

        # Create the output stream
        self.collected_data = np.array([])
        self.fs = samplerate
        self.collect_data = collect_data
        self.finished = False
        self.silent = silent
        self.output_stream = sd.OutputStream(
            channels=1,
            callback=lambda *args: self._callback(*args),
            finished_callback=lambda *args: self._finished_callback(*args),
            samplerate=samplerate)
Esempio n. 22
0
    def run(self):
        """
        The primary thread function that initializes the
        OutputStream and continuously calls the Stream
        listener to place data from the buffer into the
        Stream

        Parameters
        ----------
        None

        Returns
        -------
        None

        Raises
        ------
        None
        """
        try:
            logging.debug('Running Output Speaker thread')
            with self.waitCondition:
                self.waitCondition.wait()

                with sd.OutputStream(device=self.device,
                                     channels=2,
                                     blocksize=self.stepSize,
                                     callback=self.listener):
                    while not self.stopped:
                        # time takes up less cpu cycles than 'pass'
                        time.sleep(1)

        except Exception as e:
            logging.exception(f'Exception thrown: {e}')
Esempio n. 23
0
def main():
    outdevice = 1
    samplerate = 32000
    blocksize = 256
    source = "172.16.0.29"
    source = "localhost"

    import queue
    OUT = queue.Queue()

    def callback_out(outdata, frames, time, status):
        outdata[:] = OUT.get()

    with sd.OutputStream(
            samplerate=samplerate,
            blocksize=blocksize,
            device=outdevice,
            channels=1,
            latency='low',
            callback=callback_out,
    ), Receiver(f"tcp://{source}:5555") as stream:
        audiostream = AudioReceiver(f"tcp://{source}:5556")
        for streamtype, data in buffer(0.5, {
                "video": stream.handler,
                "audio": audiostream.handler
        }):
            if streamtype == 'video':
                display(data['arr'])
            if streamtype == 'audio':
                OUT.put(data['arr'])
Esempio n. 24
0
    def set_output_stream(self):
        """
        Opens an output stream with the currently set speaker.

        Note:
            The output stream retrieves the speaker device from self.__speaker,
            which can be set using set_speaker.

        Example:
            sound = Sound()
            sound.set_speaker('USB2.0 Device')
            sound.set_output_stream()
        """
        try:
            assert isinstance(
                self.__speaker,
                unicode), "Speaker could not be found. Speaker: " + str(
                    self.__speaker)
            self.__output_stream = sd.OutputStream(
                samplerate=self.__speaker_sample_rate,
                device=self.__speaker,
                channels=1,
                dtype="float32",
            )
        except AssertionError as e:
            print(e)
Esempio n. 25
0
def easy_sound(freq, pos):
    fbins = [
        1.570, 4.714, 7.862, 11.0186, 14.18624, 33.616, 36.7912, 40.3274,
        43.744
    ]

    stream = sd.OutputStream(dtype=np.int16, channels=2)
    stream.start()
    time = 2.0
    wave = 0
    samples = np.arange(44100 * 1 * time) / 44100.0
    for i in range(len(fbins)):
        if (fbins[i] * freq > 20000.0):
            break
        a = np.sin(np.pi * (i + 1) * pos / 1.0) / (343 * fbins[i] * freq)
        alpha = (1 / 4) * 1 * (2 - (np.sin(2 * np.pi * (i + 1)) / (np.pi *
                                                                   (i + 1))))
        a /= alpha
        print(a)
        wave += a * np.sin(2 * np.pi * (fbins[i] * freq) * samples)

    wave *= 100000000

    for i in range(len(wave)):
        # print(wave[i])
        wave[i] *= np.exp(-2.0 * (i / 44100))

    wav_wave = np.array(wave, dtype=np.int16)
    stream.write(wav_wave)
    stream.close()
    scipy.io.wavfile.write('out.wav', 44100, wav_wave)
    return wav_wave
Esempio n. 26
0
 def run(self):
     while (True):
         with sd.OutputStream(channels=1,
                              callback=self.callback,
                              samplerate=self.fs):
             while (not self.play_stopped):
                 time.sleep(.05)
Esempio n. 27
0
    def __init__(self, angular_accuracy=1, fs=48000):

        self.distance = angular_accuracy
        self.angular_accuracy = angular_accuracy

        # characteristics
        frequency = 300  # Hz
        amplitude = 0.1  # mag
        pulse_duration = 10  # cycles
        fade_length = 400  # samples
        self.gap_multi = 10  # angular distance -> gapwidt in ms * gap_multi (1° -> 1ms * gap_multi)

        # other stuff
        self.start_idx = 0
        self.fs = fs
        self.pulse = np.array([])
        self.stream = sd.OutputStream(samplerate=self.fs,
                                      channels=1,
                                      callback=self.audio_callback)

        # precalculate sinepulse
        T_sine = int(fs / frequency)
        t = np.arange(T_sine * pulse_duration)
        self.sine = amplitude * np.sin(2 * np.pi * t / T_sine)
        fade = np.arange(fade_length) / fade_length
        self.sine[:fade_length] = self.sine[:fade_length] * fade
        self.sine[-fade_length:] = self.sine[-fade_length:] * np.flip(fade)
Esempio n. 28
0
    def _check_stream(self,
                      samplerate: float = None,
                      channels: int = None) -> None:
        """This function is a hack to fix a problem with an sounddevice
        streams in an unsane state: these streams have both, `active`
        and `stopped` flag (and also the `closed` flag) set to `False`.
        Such a state seems to occur when the stream is stopped
        (or aborted) from within the stream Thread (while stopping
        or aborting from another Thread seems to be ok).
        Such unsane streams can not be restarted by calling stream.start(),
        they seem to be dead (at least I did not find a way to revive
        them). As a workaround, we simply create a new stream here to
        replace the original one.
        """
        # Check the state of the current stream
        if self._stream is not None and not self._stream.closed:
            if self._stream.active or self._stream.stopped:
                return  # Stream seems to be ok

            LOG.warning("SoundDevicePlayer: "
                        "discovered unsane stream - creating a new one ...")
            # Stream seems to be dead - copy stream parameters
            samplerate = samplerate or self._stream.samplerate
            channels = channels or self._stream.channels
            self._stream.close()

        # create a new stream
        self._stream = sd.OutputStream(samplerate=samplerate,
                                       channels=channels,
                                       callback=self._play_block,
                                       finished_callback=self._finished)
 def __init__(self,
              sampleRate,
              channels,
              blockSize,
              device=None,
              duplex=False):
     # initialise thread
     self.streams = []
     self.list = []
     # sound stream info
     self.sampleRate = sampleRate
     self.channels = channels
     self.duplex = duplex
     self.blockSize = blockSize
     self.label = getStreamLabel(sampleRate, channels, blockSize)
     if device == 'default':
         device = None
     self.sounds = []  # list of dicts for sounds currently playing
     self.takeTimeStamp = False
     self.frameN = 1
     # self.frameTimes = range(5)  # DEBUGGING: store the last 5 callbacks
     if not travisCI:  # travis-CI testing does not have a sound device
         self._sdStream = sd.OutputStream(samplerate=self.sampleRate,
                                          blocksize=self.blockSize,
                                          latency='low',
                                          device=device,
                                          channels=self.channels,
                                          callback=self.callback)
         self._sdStream.start()
         self.device = self._sdStream.device
         self.latency = self._sdStream.latency
         self.cpu_load = self._sdStream.cpu_load
     self._tSoundRequestPlay = 0
Esempio n. 30
0
    def start(self):
        """
        Start the playback
        """
        with h5py.File(self._fn, 'r') as f:
            self._ad = f['audio']
            dtype = self._ad.dtype
            dtype_str = str(dtype)
            stream = sd.OutputStream(samplerate=self.samplerate,
                                     blocksize=self.blocksize,
                                     channels=1,
                                     dtype=dtype_str,
                                     callback=self.audio_callback)

            self._running <<= True
            if self._video:
                self._vd = f['video']
                videothread = Thread(target=self.video_thread_fcn)
                videothread.start()

            with stream:
                try:
                    with self._running_cond:
                        while self._running:
                            self._running_cond.wait()
                except KeyboardInterrupt:
                    print('Keyboard interrupt. Quit playback')

            if self._video:
                videothread.join()