예제 #1
0
파일: tut2main2.py 프로젝트: ac2cz/pySdr
def audio_thread():
    print("Starting Audio")
    global reading_data
    global win
    fs = 48000
    fftLength = 255
    blocksize = 255
    bin_bandwidth = fs / fftLength
    avg_num = 10

    s = Stream(samplerate=fs, blocksize=blocksize)
    s.start()
    psd = [0] * fftLength
    while reading_data:
        data = s.read(fftLength)
        left, right = map(list, zip(*data))
        out = np.fft.rfft(left)

        psd[0] = average(psd[0],
                         calc_psd(out[0].real, out[0].real, bin_bandwidth),
                         avg_num)
        half = int(len(out))
        for k in range(1, half):
            psd[k] = average(psd[k],
                             calc_psd(out[k].real, out[k].imag, bin_bandwidth),
                             avg_num)
        psd[half - 1] = average(
            psd[k], calc_psd(out[0].imag, out[half - 1].imag, bin_bandwidth),
            avg_num)
        if (reading_data):
            win.setData(psd)
    s.stop()
예제 #2
0
    def run(self):
        with Stream(sample_rate=44100, block_length=16) as s:
            while self.running:
                vec = s.read(NUM_SAMPLES)

                # Downsample to mono
                mono_vec = vec.sum(-1) / float(s.input_channels)

                self._spectrogram = np.fft.fft(mono_vec)
예제 #3
0
def main():
    vo = VoiceOver()
    soundcard = Stream(
        blocksize=BLOCK_SIZE,
        channels=1,
        dtype='int16',
        samplerate=44100,
        callback=vo.callback,
    )
    soundcard.start()
    while True:
        time.sleep(5)
    soundcard.stop()
예제 #4
0
def play_source(source_path):
    """Play an audio file using pysoundcard."""

    from aubio import source
    from pysoundcard import Stream

    hop_size = 256
    f = source(source_path, hop_size=hop_size)
    samplerate = f.samplerate

    s = Stream(sample_rate=samplerate, block_length=hop_size)
    s.start()
    read = 0
    while 1:
        vec, read = f()
        s.write(vec)
        if read < hop_size: break
    s.stop()
예제 #5
0
def record_sink(sink_path):
    """Record an audio file using pysoundcard."""

    from aubio import sink
    from pysoundcard import Stream

    hop_size = 256
    duration = 5  # in seconds
    s = Stream(block_length=hop_size)
    g = sink(sink_path, samplerate=s.sample_rate)

    s.start()
    total_frames = 0
    while total_frames < duration * s.sample_rate:
        vec = s.read(hop_size)
        # mix down to mono
        mono_vec = vec.sum(-1) / float(s.input_channels)
        g(mono_vec, hop_size)
        total_frames += hop_size
    s.stop()
예제 #6
0
def iter_capture_and_detect_gender(sample_rate=11025,
                                   hop_size=256,
                                   confidence_threshold=0.8):
    """Capture audio and yield gender.

    Parameters
    ----------
    sample_rate : int
        Sample rate in Hertz
    confidence_threshold : float
        Pitch confidence threshold for yielding

    Yields
    ------
    gender : str
        String representing gender either 'male' or 'female'

    """
    stream = Stream(blocksize=hop_size, channels=1, samplerate=sample_rate)
    stream.start()
    try:
        while True:
            samples = stream.read(hop_size).flatten()
            pitch_and_confidence = get_pitches(samples,
                                               buf_size=hop_size,
                                               hop_size=hop_size,
                                               sample_rate=sample_rate)
            pitch = pitch_and_confidence[0, 0]
            confidence = pitch_and_confidence[0, 1]
            if pitch > 145:
                gender = 'female'
            else:
                gender = 'male'
            if confidence >= confidence_threshold:
                yield gender
    except KeyboardInterrupt:
        pass
    stream.stop()
예제 #7
0
def record_sink(sink_path):
    """Record an audio file using pysoundcard."""

    from aubio import sink
    from pysoundcard import Stream

    hop_size = 256
    duration = 5  # in seconds
    s = Stream(blocksize=hop_size, channels=1)
    g = sink(sink_path, samplerate=int(s.samplerate))

    s.start()
    total_frames = 0
    try:
        while total_frames < duration * s.samplerate:
            vec = s.read(hop_size)
            # mix down to mono
            mono_vec = vec.sum(-1) / float(s.channels[0])
            g(mono_vec, hop_size)
            total_frames += hop_size
    except KeyboardInterrupt:
        duration = total_frames / float(s.samplerate)
        print("stopped after %.2f seconds" % duration)
    s.stop()
예제 #8
0
import sys
import time
import numpy as np
from scipy.io.wavfile import read as wavread
from pysoundcard import Stream, continue_flag, complete_flag
"""Play an audio file."""

fs, wave = wavread(sys.argv[1])
wave = np.array(wave, dtype=np.float32)
wave /= 2**15  # normalize -max_int16..max_int16 to -1..1
play_position = 0


def callback(in_data, out_data, time_info, status):
    global play_position
    out_data[:] = wave[play_position:play_position + block_length]
    # TODO: handle last (often incomplete) block
    play_position += block_length
    if play_position + block_length < len(wave):
        return continue_flag
    else:
        return complete_flag


block_length = 16
s = Stream(sample_rate=fs, block_length=block_length, callback=callback)
s.start()
while s.is_active():
    time.sleep(0.1)
예제 #9
0
"""
import sys, os
import numpy as np
from scipy.io.wavfile import read as wavread
from pysoundcard import Stream

()

path = '/home/muenker/Daten/share/Musi/wav/'
#path = '../_media/'
#filename = 'chord.wav'
filename = '07 - Danny Gottlieb with John McLaughlin - Duet.wav'
filename = 'Ole_16bit.wav'  #
filename = '01 - Santogold - L.E.S Artistes.wav'
filename = '01 - Santogold - L.E.S Artistes_20s.wav'
#filename = 'ComputerBeeps2.wav'
filename = 'SpaceRipple.wav'

fs, wave = wavread(os.path.join(path, filename))
"""Play an audio file."""

#fs, wave = wavread(sys.argv[1])
wave = np.array(wave, dtype=np.float32)
wave /= 2**15  # normalize -max_int16..max_int16 to -1..1

blocksize = 512
s = Stream(samplerate=fs, blocksize=blocksize)
s.start()
s.write(wave)
s.stop
예제 #10
0
__test__ = False

import imp
import numpy as np
import pyfilterbank
from soundfile import SoundFile
from pysoundcard import Stream


filename = r'bonsai.wav'

ofb = filterbank.OctaveFilterbank(nth_oct=3.0, start_band=-18, end_band=12, lphp_bounds=True, filterfun='cffi')

st = Stream(input_device=False)
sf = SoundFile(filename)

st.start()

def play_further(nblocks=120, blen=4096):
    states = np.zeros(2)
    for i in range(nblocks):
        x = sf.read(blen)[:,0]
        y, states = ofb.filter(x,states=states)
        out = y.sum(axis=1).values.flatten()
        st.write(out)

play_further()
예제 #11
0
from pysoundcard import Stream
"""Loop back five seconds of audio data."""

fs = 44100
block_length = 16
s = Stream(sample_rate=fs, block_length=block_length)
s.start()
for n in range(int(fs * 5 / block_length)):
    s.write(s.read(block_length))
s.stop()
예제 #12
0
 def __enter__(self):
     self._audio_stream = Stream(samplerate=self._rate, blocksize=self._blocksize)
     self._audio_stream.start()
     self.closed = False
예제 #13
0
파일: main.py 프로젝트: bastibe/QtWorkshop
 def run(self):
     with Stream() as s:
         while self.soundFile.seek(0) < len(self.soundFile):
             s.write(self.soundFile.read(1024))
             self.frameChanged.emit(self.soundFile.seek(0))
         self.frameChanged.emit(0)
예제 #14
0
import sys
import numpy as np
from scipy.io.wavfile import read as wavread
from pysoundcard import Stream
"""Play an audio file."""

fs, wave = wavread(sys.argv[1])
wave = np.array(wave, dtype=np.int16)

blocksize = 256
s = Stream(samplerate=fs, blocksize=blocksize, dtype='int16')
s.start()
while True:
    s.write(wave[0:(1024 * 100)])
s.stop()
예제 #15
0
from pysoundcard import Stream, continue_flag
import time

"""Loop back five seconds of audio data."""

def callback(in_data, out_data, time_info, status):
    out_data[:] = in_data
    return continue_flag

with Stream(sample_rate=44100, block_length=16, callback=callback):
    time.sleep(5)
예제 #16
0
    inputdata.append(line)
header = inputdata[0]
hop_s = int(header.rstrip("\n").split("\t")[0])
frames_limit = int(header.rstrip("\n").split("\t")[1])
sample_rate = int(header.rstrip("\n").split("\t")[2])
inputdata = inputdata[1:]

for line in inputdata:
    data_point = np.asarray(line.rstrip("\n").split("\t")[:-1]).astype(
        np.float32)
    data_point = data_point.reshape((frames_limit, hop_s))
    data.append(data_point)
data = np.asarray(data)
print("Loaded data " + str(data.shape))

s = Stream(samplerate=sample_rate, blocksize=hop_s)
beat_no = 0

#Get input from user and save to file
outputfilename = "_".join(data_name.split('_')[0:-1]) + "_labelled.txt"
outputfile = open(outputfilename, "w")

#Checking if Auto Mode
default_chord = ""
if (getClassLabel((data_name.split('_'))[0]) != -1):
    default_chord = (data_name.split('_'))[0]
    print("Auto mode")

output_data = []
previous_chord = "null"
num_chords = 0