예제 #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
class SysAudioStream(object):
    """Loop back system audio."""
    def __init__(self, rate, blocksize):
        self._rate = rate
        self._blocksize = blocksize
        self._buff = queue.Queue()
        self.closed = True

    def __enter__(self):
        self._audio_stream = Stream(samplerate=self._rate, blocksize=self._blocksize)
        self._audio_stream.start()
        self.closed = False



    def __exit__(self, type, value, traceback):
        self._audio_stream.stop()
        self.closed = True
        # Signal the generator to terminate so that the client's
        # streaming_recognize method will not block the process termination.
        self._buff.put(None)

    def generator(self):
        while not self.closed:
            # Use a blocking get() to ensure there's at least one chunk of
            # data, and stop iteration if the chunk is None, indicating the
            # end of the audio stream.
            chunk = self._audio_stream.read(16)
            if chunk is None:
                return
            data = [chunk]

            # Now consume whatever other data's still buffered.
            # while True:
            #     try:
            #         chunk = self._buff.get(block=False)
            #         if chunk is None:
            #             return
            #         data.append(chunk)
            #     except queue.Empty:
            #         break

            yield b''.join(data)
예제 #3
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()
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()
예제 #5
0
class InputStream(Stream):

    def __init__(self, device=None):
        super(self.__class__, self).__init__()
        self.device = device if device is not None else self._findDevice()
        self.sr = consts.sr
        self.inputStream = PyScStream(
            sample_rate=self.sr, block_length=consts.window_hop,
            callback=self.inputStreamCallback, input_device=self.device)
        self.iteration = 0

    def _findDevice(self):
        inputPriority = [
            "FastTrack Pro",
            "Built-in Input",
            "Soundflower (2ch)",
        ]
        for input_ in inputPriority:
            for dev in pysoundcard.devices():
                if dev['name'] == input_ and dev['input_channels'] > 0:
                    return dev

    def inputStreamCallback(self, inData, numFrames, timeInfo, status):
        '''
        Wrap our stream callback in the default pysoundcard callback
        '''
        self.iteration += 1
        if self.iteration % 3 == 0:
            print "%.2f" % np.sum(inData)
        self.enqueueChunk(inData)
        return (np.zeros((numFrames, 2)), pysoundcard.continue_flag)

    def read(self, *args, **kwargs):
        return self.inputStream.read(*args, **kwargs)

    def start(self):
        self.inputStream.start()

    def stop(self):
        self.inputStream.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 track_energy():
    """Track attacks of instrument, maintain global float energy"""

    global energy
    energy = 0.25

    win_size = 512                 # fft size
    hop_size = 256
    s = Stream(block_length = hop_size)

    o = onset("default", win_size, hop_size, s.sample_rate)


    come_up_steps = ceil(come_up_secs * s.sample_rate/hop_size)
    built_energy = 0
    built_steps = 0

    onsets = 0
    

    s.start()
    while True:
        vec = s.read(hop_size)
        # mix down to mono
        mono_vec = vec.sum(-1) / float(s.input_channels)
        if o(mono_vec):
            print "beat" + str(onsets)
            onsets += 1
            built_energy = (nu * (energy + built_steps * built_energy) + (1-nu) - energy)/(built_steps+come_up_steps)
            built_steps += come_up_steps
        if built_steps == 0 :
            energy = (1-eta) * energy
        else:
            energy += built_energy
            built_steps -= 1
#        print "energy = %f, total = %f" % (energy,energy + built_energy * built_steps)
    s.stop()
예제 #8
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()
예제 #9
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()
예제 #10
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()
예제 #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()
# Rauschen abspielen und kontinuierlich in Blöcken aufnehmen

from pysoundcard import Stream
import pysoundcard
import numpy as np

fs = 44100
block_length = 1024*8
s = Stream(sample_rate=fs, block_length=block_length)
time = 1 # Laenge des Rauschens in Sekunden
noise = np.random.randn(block_length,2)/20.0 
n_blocks = int(fs*time/block_length)

# für das erste hinzufügen des ersten arrays einen start arry
# in passender größe, hier erstmal Nullen
rec_file=np.zeros([block_length,2],float) 

s.start()
for n in range(n_blocks):
	s.write(noise)
	rec = s.read(block_length)
	rec_file=np.vstack([rec_file,rec]) # hinzufügen des aufgenommenen blocks zu rec_file als zeilenvektor in einem array!
	
#s.write(rec_file)
#print(rec_file)
s.stop()
n_down_plot = 50 #Variable Anzahl Plotts pro Sekunde

############ Stream mit Zugriffswegen fuer externe Soundkarte ##########
s = Stream(sample_rate = fs, 
           block_length = block_length,
           input_device_index = 1, #im CommandWindow den Weg herausfinden mit import pyaudio, py=pyaudio.PyAudio(), pa.get_device_info_by_index(NUMMERVERSUCH)
           output_device_index = 4) 

fig, ax = plt.subplots()
s.start()
plt.show(block=False) #Plot wird im Fenster gelöscht und neu geschrieben

ca_whole_record = []
num_of_blocks = int(fs*record_seconds/block_length)
line, = ax.plot(np.random.randn(num_of_blocks)*15-50) #Skalierung der y-Achse
pegel = np.zeros(num_of_blocks) #Nullvektor erstellen als Ausgang

for n in range(num_of_blocks): #geht die Schleife solange durch, bis 
    ca_record = s.read(block_length)
    pegel[n] = 10*np.log10(np.sum(np.square(ca_record))/block_length) #Pegel auf logarithmischer y-Achse darstellen 
    ca_whole_record.append(ca_record) #haengt alle in blocklaenge aufgenommenes Array

    if np.mod(n, n_down_plot) == 0: #Modul-Befehl fuer Rest berechnen, damit nur soviel wie n_down_plot im Plotfenster gezeigenangezeigt wird
        line.set_ydata(pegel)
        ax.draw_artist(ax.patch)
        ax.draw_artist(line)
        fig.canvas.update()
        fig.canvas.flush_events()
s.stop()
print ("* done recording")
예제 #14
0
from pysoundcard import Stream

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

fs = 44100
blocksize = 16
s = Stream(samplerate=fs, blocksize=blocksize)
s.start()
for n in range(int(fs * 5 / blocksize)):
    s.write(s.read(blocksize))
s.stop()
예제 #15
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()