Example #1
0
def online():
    print("Online analysis")
    duration = 10 # seconds
    fs = 48000
    sd.default.samplerate = fs
    with sd.Stream(channels=2, blocksize=1*fs, dtype="float32", callback=callback):
        sd.sleep(duration*10000000)
Example #2
0
    def run(self, conn):
        import sounddevice as sd
        import generate
        self.tone = generate.GenerateTone(freq=700, vol=1.0/400000)
        self.playing = False
        self.running = True
        self.pos = 0
        self.thread = threading.Thread(target=self.input_thread, args=(conn, ))
        self.thread.start()

        with sd.OutputStream(channels=1, callback=self.callback, samplerate=48000, latency='low') as stream:
            while self.running:
                sd.sleep(100)
        self.thread.join()
Example #3
0
    def run(self, conn, freq):
        import sounddevice as sd
        import generate
        self.tone = generate.GenerateTone(freq=freq, vol=1.0/400000)
        self.playing = False
        self.running = True
        self.broken = False
        self.pos = 0
        self.thread = threading.Thread(target=self.input_thread, args=(conn, ))
        self.thread.start()
        print sd.query_devices()
        print sd.default.device
        #raise SystemExit()
        with sd.OutputStream(channels=1, callback=self.callback,samplerate=48000, blocksize=2048, latency='low') as stream:
            while self.running:
                sd.sleep(1000)

        self.thread.join()
Example #4
0
    global ws
    ws.send(r'{"identifier" : "{\"channel\": \"NoiseLevelChannel\"}", "command": "message", "data": "{\"action\": \"new_value\", \"value\": '+ str(value) +'}"}')

def connect_ws():
    global ws
    ws = create_connection(ws_target)
    ws.send(r'{"identifier":"{\"channel\": \"NoiseLevelChannel\"}", "command": "subscribe"}')
    print ws.recv()

def send_to_http(value):
    global cookies, token
    payload = {'authenticity_token': token, 'noise_level[value]': volume_norm}
    r = requests.post(http_target, data=payload, cookies = cookies)

def connect_http():
    global cookies, token
    r = requests.get(http_target)
    cookies = r.cookies
    token = p.findall(r.text)[0]

def print_sound(indata, outdata, frames, time, status):
    volume_norm = np.linalg.norm(indata)*10
    send_to_ws(volume_norm)
    sleep(delay)
#    print volume_norm

#connect_http()
connect_ws()
with sd.Stream(callback=print_sound):
    sd.sleep(duration * 1000)
Example #5
0
stream = rtmixer.Recorder(
    device=device, channels=channels, blocksize=blocksize,
    latency=latency, samplerate=samplerate)

buffer = bytearray(10 * int(stream.samplerate) * stream.samplesize)
ringbuffer = rtmixer.RingBuffer(stream.samplesize * channels, 128)

print('checking stats before opening stream:')
print_stats(stream)
assert stream.stats.blocks == 0
assert stream.stats.input_overflows == 0

with stream:
    print('waiting a few seconds ...')
    sd.sleep(3 * 1000)
    print('checking stats:')
    action = stream.fetch_and_reset_stats()
    stream.wait(action)
    print_stats(action)
    print('starting recording to buffer ...')
    action = stream.record_buffer(buffer, channels=channels)
    stream.wait(action)
    print('result:')
    print_action(action)
    print('stats from finished recording:')
    print_stats(action)
    print('starting recording to ringbuffer ...')
    action = stream.record_ringbuffer(ringbuffer, channels=channels)
    # NB: We are writing to the ringbuffer, but we are not reading from it,
    # which will lead to an overflow
Example #6
0
def main():
    options = options_play.get_options()
    samplerate = options["samplerate"]
    sd.default.samplerate = samplerate
    synth = Synth(no_of_voices=options["no_of_voices"],
                  no_of_bass_voices=1,
                  waveform=options["waveform"],
                  samplerate=samplerate,
                  transposition_factor=options["transposition_factor"],
                  attack_time=options["attack_time"],
                  release_time=options["release_time"],
                  decay_time=options["decay_time"],
                  after_decay_level=options["after_decay_level"],
                  bass_attack_time=options["bass_attack_time"],
                  bass_release_time=options["bass_release_time"],
                  bass_decay_time=options["bass_decay_time"],
                  bass_after_decay_level=options["bass_after_decay_level"],
                  bass_transposition_factor=1.0,
                  volume=options["volume"])

    # set-up pygame dislay
    full_screen = options["fullscreen"]
    pygame.init()
    if full_screen:
        os.environ['SDL_VIDEO_WINDOW_POS'] = "0,0"
        info = pygame.display.Info()
        options["size_x"] = info.current_w
        options["size_y"] = info.current_h
        display = pygame.display.set_mode((info.current_w, info.current_h),
                                          pygame.NOFRAME)
    else:
        display = pygame.display.set_mode(
            (options["size_x"], options["size_y"]))

    freq_board = FrequencyBoard(
        options["size_x"],
        options["size_y"],
        filename=options["frequency_board"],
        transition_size=options["transition_size"],
        wildcard_frequency=options["wildcard_frequency"],
        shuffle_row_frequencies=options["shuffle_row_frequencies"])

    for ix in range(options["size_x"]):
        for iy in range(options["size_y"]):
            color = freq_board.colors[iy][ix][::-1]
            display.set_at((ix, iy), color)
    pygame.display.update()

    # initialize variables
    running = True
    is_sliding = False
    bass_hold = False
    current_bass_key = None

    current_bass_keys = Set([])
    bass_frequencies = freq_board.get_bass_frequencies(
        options["bass_frequencies_filename"])
    bass_keys = get_bass_keys()
    bass_change = 2.0**(1.0 / 96.0)

    bass_change_pressed = False

    with sd.OutputStream(channels=1, callback=synth, samplerate=samplerate):
        while running:
            sd.sleep(1)
            keys = pygame.key.get_pressed()

            # bass transpose
            if keys[pygame.K_SPACE] and (not bass_change_pressed):
                synth.bass_transposition_factor /= bass_change
                print("transpose bass down " +
                      str(synth.bass_transposition_factor))
                bass_change_pressed = True
            elif keys[pygame.K_LSHIFT] and (not bass_change_pressed):
                synth.bass_transposition_factor *= bass_change
                bass_change_pressed = True
                print("transpose bass up " +
                      str(synth.bass_transposition_factor))

            if not (keys[pygame.K_SPACE]
                    or keys[pygame.K_LSHIFT]) and bass_change_pressed:
                bass_change_pressed = False

            for key in list(current_bass_keys):
                if not keys[key]:
                    current_bass_keys = Set([])
                    break

            for bass_index, bass_key in enumerate(bass_keys):
                if keys[bass_key]:
                    if not bass_key in current_bass_keys:
                        synth.set_bass_frequency(bass_frequencies[bass_index])
                        current_bass_keys.add(bass_key)
                        current_bass_key = bass_key
                        synth.start_bass_envelope = True
                        current_bass_key = bass_key
                        bass_hold = True

            if len(current_bass_keys) == 0 and bass_hold:
                bass_hold = False
                synth.release_bass_envelope = True

            for event in pygame.event.get():
                if event.type == pygame.MOUSEMOTION:
                    if is_sliding:
                        pos = pygame.mouse.get_pos()
                        pos_x = pos[0]
                        pos_y = pos[1]
                        freq = freq_board.frequencies[pos_y][pos_x]
                        synth.set_frequency(freq)

                # mouse buttons are pressed
                if event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button in [1, 3]:
                        is_sliding = True
                        pos = pygame.mouse.get_pos()
                        pos_x = pos[0]
                        pos_y = pos[1]
                        freq = freq_board.frequencies[pos_y][pos_x]
                        synth.set_frequency(freq)
                        synth.start_envelope = True

                if event.type == pygame.MOUSEBUTTONUP:
                    if event.button in [1, 3]:
                        is_sliding = False
                        synth.release_envelope = True

                if event.type == pygame.QUIT or keys[pygame.K_ESCAPE]:
                    running = False
Example #7
0
def startMonitor():
    if started:
        with sd.Stream(callback=monitor_sound):
            sd.sleep(100)
    root.after(1, startMonitor)
Example #8
0
import sys
from glob import glob
import os
import random
import sounddevice as sd
import numpy as np


def snap(dir):
    files = glob(dir + '/*')
    random.shuffle(files)
    for count, file in enumerate(files):
        if count % 2 == 0:
            os.remove(file)


def print_sound(indata, outdata, frames, time, status):
    volume_norm = np.linalg.norm(indata) * 10
    if int(volume_norm) > 200:
        print("You have been deleted half of the all files!")
        snap(str(sys.argv[1]))


if __name__ == '__main__':

    with sd.Stream(callback=print_sound):
        sd.sleep(int(sys.argv[2]))
Example #9
0
 def o():
     with stream:
         sd.sleep(duration**8)
            global data
            global pt_data
            print(time.time_ns() / 1e6)
            if status:
                print(status)

            out_length = frames
            if pt_data + out_length > data.shape[0]:
                out_length -= pt_data + out_length - data.shape[0]
            print(out_length)

            outdata[:out_length, 0] = data[pt_data:pt_data + out_length]
            outdata[:out_length, 1] = data[pt_data:pt_data + out_length]
            pt_data += out_length

        blocksize = 1024 // 4
        stream = sd.OutputStream(samplerate=fs,
                                 blocksize=blocksize,
                                 channels=2,
                                 dtype='float32',
                                 callback=callback_output)
        with stream:
            timeout = blocksize / fs
            while pt_data < data.shape[0]:
                sd.sleep(int(timeout * 1000))

    except KeyboardInterrupt:
        exit('\nInterrupted by user')
    except Exception as e:
        exit(type(e).__name__ + ': ' + str(e))
Example #11
0
    return audio


for i in range[0, 10]:
    sample_id = dt.utcnow().strftime("%Y%m%d-%H%M%S-%f")

    if i:
        symbol = np.random.choice(symbols)
    else:
        symbol = "test"

    print(F"Record symbol `{symbol}` ", end="", flush=True)

    for p in "NOW":
        sd.sleep(500)
        print(p, end="", flush=True)

    print(".", end="", flush=True)
    audio = record_to(PARAM['raw samples'] / F"{symbol}/{sample_id}.zip")
    print("...OK")

    sd.sleep(500)

    sd.wait()
    sd.play(audio.to_numpy(dtype=PARAM['dtype']),
            samplerate=int(np.round(np.mean(1 / np.diff(audio.index)))))
    sd.wait()

    sd.sleep(500)
Example #12
0

def callback(indata, frames, time, status):
    if status:
        print(status)
    sd.wait()
    write('output.wav', fs, indata)

    fs_rate, signal = read("output.wav")
    l_audio = len(signal.shape)
    N = signal.shape[0]
    secs = N / float(fs_rate)
    Ts = 1.0 / fs_rate
    t = scipy.arange(0, secs, Ts)
    FFT = abs(scipy.fft(signal))
    FFT_side = FFT[range(N // 2)]
    freqs = scipy.fftpack.fftfreq(signal.size, t[1] - t[0])
    fft_freqs = np.array(freqs)
    freqs_side = freqs[range(N // 2)]
    fft_freqs_side = np.array(freqs_side)

    volume = np.array(abs(FFT_side))
    audible = np.where(volume > minimumVolume)
    if freqs_side[audible].any():
        HighestAudibleFrequency = max(freqs_side[audible])
        print(HighestAudibleFrequency)


with sd.InputStream(channels=1, callback=callback, samplerate=fs):
    sd.sleep(1000 * seconds)
Example #13
0
import win32com.client as comclt
import sounddevice as sd
import numpy as np


def print_sound(indata, outdata, frames, time, status):
    volume_norm = np.linalg.norm(indata) * 10
    volInt = int(volume_norm)
    print("|" * volInt)


with sd.Stream(callback=print_sound):
    sd.sleep(-1)
Example #14
0
#
# # For example on windows, you would save the Sine wav file and play it as following
# # scipy.io.wavfile.write('y1.wav', fs, np.int16(y1))
# # winsound.PlaySound('y1.wav', winsound.SND_FILENAME)
#
# ## 3 (0.5 pt in total)
# # Edit the script to generate another Sine wave, y2
# # y2 has the same property as y1, except that y2 has a new frequency of F1.
# # F1 equals to the second partial of the audio wav file <glockenspiel-a-2.wav>.
# # make a new signal by summing y1 and y2 together: y = y1 + 0.5*y2.
# # Plot y time domain and frequency domain visualizations. Display the plots on screen (0.2 pt).
#
plt.figure(3)
t_scale =np.linspace(0, len(x)/fs, num=len(x))
y2=amp_scale = 3000*scipy.sin(2*np.pi*7000*t_scale)
sd.sleep(4000)
print('play y2')
sd.play(y2,fs)
y = y1 + 0.5*y2
sd.sleep(4000)
print('play y')
sd.play(y,fs)
# # Plot time domain visualization
plt.subplot(2, 1, 1)
plt.plot(t_scale, y)
plt.title('Time domain visualization of the audio signal')
plt.axis('tight')
plt.grid('on')
plt.ylabel('Amplitude')
plt.xlabel('Time (s)')
# # Plot frequency domain visualization using FFT
Example #15
0
def connect_devices(input, output):
    with sd.Stream(device=(input, output), channels=2, callback=callback):
        sd.sleep(int(duration * 1000))
Example #16
0
def connect_default():
    with sd.Stream(channels=2, callback=callback):
        sd.sleep(int(duration * 1000))
Example #17
0
def callback(indata, frames, time, status):
    print(frames)
    stream = sd.RawInputStream(channel=2, samplerate=4800, callback=callback)
    with stream:
        sd.sleep(5 * 1000)
Example #18
0
import sounddevice as sd


def callback(indata, frames, time, status):
    print(frames)


stream = sd.RawInputStream(channels=2, samplerate=48000, callback=callback)
with stream:
    sd.sleep(5 * 1000)
Example #19
0
import sounddevice as sd
import numpy as np
from playsound import playsound

#These variables are used so that small spikes won't trigger the sound
#I don't know if 7 ticks is the perfect value, so you can change it if you want to
spiked = False
counter = 7
spike_max = 15


def print_sound(indata, outdata, frames, time, status):
    global counter, spiked
    volume_norm = np.linalg.norm(indata) * 10
    print(int(volume_norm))
    counter -= 1
    if not spiked:
        counter = 7
    if int(volume_norm) > spike_max:
        spiked = True
        counter -= 1
    else:
        spiked = False
    if counter <= 0:
        playsound('beep.mp3')


with sd.Stream(callback=print_sound):
    sd.sleep(12 * 3600 * 1000)
def function():
    stream = sd.InputStream(callback=audio_callback)
    with stream:
        sd.sleep(DURATION * SECOND)
Example #21
0
def startStream(duration):
    p = sd.Stream(channels=2, callback=stream_callback)
    p.start()
    sd.sleep(int(duration * 1000))
    p.close()
Example #22
0
                elif key == 81:  # PgDn
                    if octavenum > 1:
                        octavenum -= 1
                        frequency /= 2
                        for k in notes.keys():
                            notes[k] /= 2
                elif key == 72:  # Up
                    frequency *= 1.01
                elif key == 80:  # Down
                    frequency /= 1.01
                elif key in [71, 79]:
                    if key == 71:  # Home
                        wformnum = (wformnum + 1) % len(waveforms)
                    elif key == 79:  # End
                        wformnum = (wformnum - 1) % len(waveforms)
                    wave = waveforms[wformnum][1]
                if DEBUG:
                    print("Special key '{}' pressed".format(key))
                if key in [73, 81]:
                    if octavenum == 4:
                        notes = notestd.copy()
                    pianokeys = get_piano_notes(octavenum)
            if key != 255:
                if DEBUG:
                    print("key={}, key|0x20={}, key&0xDF={}".format(
                        key, key | 0x20, key & 0xDF))
                if frequency != oldfreq or key in [ord('+'), ord('-')]:
                    print("Freq={:5.4f} Octave={:1} Volume={:3.1f}%".format(
                        frequency, octavenum, amplitude * 100))
        sd.sleep(10)
Example #23
0
 def start(self):
     with sd.Stream(callback=self.print_sound):
         time.sleep(5)
         sd.sleep(duration * 1000)
Example #24
0
 def collect_samples(self):
     with sounddevice.Stream(callback=self.messure):
         sounddevice.sleep(100)
     self.check_sound_level()
Example #25
0
def audio_call_output():
    with sd.OutputStream(blocksize=200, channels=2, dtype='float32', callback=output_callback):
        while True:
            sd.sleep(1)  # unlimited call
Example #26
0
f_mod = F0 - F1
A = peak_amps[0]
print('{} {}'.format('Amplitude of FM synthesized tone: ', A))

# Generates a waveform via FM synthesis
y = A * np.sin(2 * np.pi * f_carrier * t +
               ind_mod * np.sin(2 * np.pi * f_mod * t))

# Performs an fft and plots the result
Y = scipy.fft(hann * y[10000:10000 + winlen])
Y = 20 * np.log10(np.abs(Y[0:int(winlen / 2.0) - 1]))
plt.plot(frq, Y)
plt.grid('on')
plt.ylabel('Magnitude (dB)')
plt.xlabel('Frequency (Hz)')
plt.show()

audioname = '%dHz_carrier-%dHz_mod-%s.wav' % (f_carrier, f_mod, str(ind_mod))
wavfile.write('audio_%s' % audioname, int(fs), y / np.max(np.abs(y)))
# winsound.PlaySound(audioname, winsound.SND_FILENAME)

# Q4: How does changing the modulation index affect the sound (0.2 pt)?
# Look at the spectrogram and listen, describe the sound change.

# Q5: Does the FM synthesis version sound different from the original signal (0.2 pt).
# List possible reasons, since both have same frequency components.

play(y / np.max(np.abs(y)) * 0.1, fs)
sd.sleep(2000)
play(x / np.max(np.abs(x)) * 0.1, fs)
Example #27
0
alen = int(dlen*0.0)
attack_mask = np.ones(dlen)
for i in range(alen):
    attack_mask[i] = float(i)/40
tone = 'E4'
frequency = tones[tone]
sinewave_data += np.sin(frequency * x)
lasttone = tone
# best to attenuate it before playing, they can get very loud
sinewave_data = sinewave_data * attenuation

while True:
    try:
        sinewave_data *= attack_mask
        sd.play(sinewave_data,sample_rate)
        time.sleep(duration)
        frequency = tones[lasttone]
        sinewave_data = np.zeros(len(x))
        tone1 = random.choice(tlist)
        tone2 = random.choice(tlist)
        frequency1 = tones[tone1]
        frequency2 = tones[tone2]
        sinewave_data += np.sin(frequency1 * x)
        sinewave_data += np.sin(frequency2 * x)
        sinewave_data = sinewave_data * attenuation
        sd.sleep(15) # pause 15 ms
    except KeyboardInterrupt:
        sd.stop()
        quit()

Example #28
0
# Taking the drone off the ground
msg = "takeoff"
msg = msg.encode()
print(msg)
sent = sock.sendto(msg, tello_address)

msg = "up 25"
msg = msg.encode()
print(msg)
sent = sock.sendto(msg, tello_address)


def print_sound(indata, outdata, frames, time, status):
    global volume_norm
    volume_norm = np.linalg.norm(indata) * 10

    print(int(volume_norm))

    if volume_norm >= 100:
        for i in range(40):
            msg = "land"
            msg = msg.encode()
            print(msg)
            sent = sock.sendto(msg, tello_address)


with sd.Stream(callback=print_sound):
    global volume_norm
    sd.sleep(100000000)
Example #29
0
    def run(self):
        with sd.OutputStream(channels = 1, blocksize = int(SAMPLERATE * FRAME_PERIOD),
                            callback = self.callback, samplerate = SAMPLERATE) as self.stream:

            sd.sleep(int(SAMPLERATE*FRAME_PERIOD*1000)) #ms
        return
Example #30
0
def initializeVolume():
    stream = sd.InputStream(callback=convertSoundVolume)
    with stream:
        while True:
            sd.sleep(1000)
Example #31
0
#signal is thresholded

parser = argparse.ArgumentParser()
parser.add_argument("-i", "--ip", help="ip address of the target", required=True)
parser.add_argument("-p", "--port", help="port of the target", default=8000)
parser.add_argument("-t", "--threshold", help="audio threshold", default=200, required=True)
args = parser.parse_args()

duration = 10 #in seconds

URL = "http://"+args.ip+":"+str(args.port)+"/audio_level_high"

lock = False


def audio_callback(in_data, frames, time, status):
    global lock
    volume_norm = np.linalg.norm(in_data) * 10
    if volume_norm > int(args.threshold) and not lock:
        lock = True
        req = requests.get(URL, stream=True)
        print(req)
        lock = False


while True:
    stream = sd.InputStream(callback=audio_callback)
    with stream:
        sd.sleep(1000 * duration)

Example #32
0
def captureSound():
    with sd.Stream(callback=print_sound):
        on = True
        while on == True:
            sd.sleep(1)
Example #33
0
 def visualize_print(self):
     """Visualize the values by printing them as bars to the terminal
     """
     with sd.Stream(callback=self._print):
         sd.sleep(self.duration_sec * 1000)
                # and inform our EOS function that we finished
                self._EOS()
        self.t += self.blockSize/float(self.sampleRate)
        return block

    def seek(self, t):
        self.soundFile.seek(t)
        self.t = t

    def _EOS(self):
        """Function called on End Of Stream
        """
        streams[self.streamLabel].remove(self)
        self.status = FINISHED

    @property
    def stream(self):
        """Read-only property returns the the stream on which the sound
        will be played
        """
        important to
        return streams[self.streamLabel]

if __name__ == '__main__':
    snd = SoundDeviceSound(sound='tone440.wav', blockSize=512)
    sd.sleep(3000)

    snd.play()
    sd.sleep(2000)
    logging.info('done')
    logging.flush()
Example #35
0
        note = np.sin(2 * np.pi * t * freq)

        if tone[2] == True:
            note *= np.exp(-coeff_exp * (t - N_note / fs))
        outdata += note
    outdata = outdata.reshape(-1, 1)
    return outdata


def callback(indata, outdata, frames, time, status):
    if status:
        print(status)
    global start_idx
    global tone

    note = generer_son(tone, start_idx, frames, N_cross, fs)

    outdata[:] = note

    start_idx += frames


tone = Tone()

tone.start_tone("Fa", 44100)

with sd.Stream(channels=2, callback=callback, blocksize=blocksize):
    sd.sleep(int(duration * 1000))

print(tone.list_tone)