예제 #1
0
    def refresh_audio_setup(self):
        #init mic recording and sound playback

        sd._terminate()
        sd._initialize()

        inDev, outDev = self.audio_devices()

        try:
            inDevId = inDev[0][0]
            self.rec_stream = self.p.open(format=self.FORMAT,
                                          channels=self.CHANNELS,
                                          rate=self.RATE,
                                          input=True,
                                          frames_per_buffer=self.CHUNK,
                                          input_device_index=inDevId)
        except:
            pass

        try:
            outDevId = outDev[0][0]
            self.play_stream = self.p.open(format=self.FORMAT,
                                           channels=self.CHANNELS,
                                           rate=self.RATE,
                                           output=True,
                                           frames_per_buffer=self.CHUNK,
                                           output_device_index=outDevId)
        except:
            pass

        return inDev, outDev
예제 #2
0
    def single_measurement(self, type=None):

        # little workaround of a problem with using ASIO from multiple threads
        # https://stackoverflow.com/questions/39858212/python-sounddevice-play-on-threads
        default_device = sd.query_devices(sd.default.device[0])
        default_api = sd.query_hostapis(default_device['hostapi'])
        if default_api['name'] == 'ASIO':
            sd._terminate()
            sd._initialize()

        self.recorded_sweep_l = []
        self.recorded_sweep_r = []
        self.feedback_loop = []

        if type is 'hpc':
            excitation = self.excitation_hpc
        else:
            excitation = self.excitation

        if not self.dummy_debugging:
            time.sleep(0.3)

        try:
            sd.check_input_settings(channels=self.num_input_channels_used)
            sd.check_output_settings(channels=self.num_output_channels_used)
        except:
            print(
                "Audio hardware error! Too many channels or unsupported samplerate"
            )
            return

        # do measurement
        recorded = sd.playrec(excitation,
                              channels=self.num_input_channels_used)
        sd.wait()

        # get the recorded signals
        if self.channel_layout_input[0] >= 0:
            self.recorded_sweep_l = recorded[:, self.channel_layout_input[0]]
        else:
            self.recorded_sweep_l = np.zeros(np.size(recorded, 0))

        if self.channel_layout_input[1] >= 0:
            self.recorded_sweep_r = recorded[:, self.channel_layout_input[1]]
        else:
            self.recorded_sweep_r = np.zeros(np.size(recorded, 0))

        if self.feedback_loop_used:
            self.feedback_loop = recorded[:, self.channel_layout_input[2]]
            if abs(self.feedback_loop.max()) < 0.0001:
                self.feedback_loop = np.random.random_sample(
                    self.feedback_loop.shape
                ) * 0.000001  # to avoid zero-division errors
        else:
            # if no FB loop, copy from original excitation sweep
            if type is 'hpc':
                self.feedback_loop = self.sweep_hpc_mono[:, 0]
            else:
                self.feedback_loop = self.sweep_mono[:, 0]
예제 #3
0
 def _getSDAudioDevices(cls):
     # To update the list of devices
     # Sadly this only works on Windows. Linux hangs, MacOS crashes.
     if isWindows():
         sd._terminate()
         sd._initialize()
     devices: sd.DeviceList = sd.query_devices()
     return devices
예제 #4
0
def record_audio(myrecording):
    sd._terminate()
    sd._initialize()
    fs = 44100  # Sample rate
    seconds = 16  # Duration of recording
    # sd.default.device = 9
    print(type(myrecording))
    myrec = sd.rec(int(seconds * fs), samplerate=fs, channels=2)
    sd.wait()
    myrecording.put(myrec)
예제 #5
0
def main():
    parser = argparse.ArgumentParser(
        description='Read and process audio input.')
    parser.add_argument('-d',
                        '--device',
                        type=int,
                        help='Index of the input device',
                        default=None)
    parser.add_argument('-l',
                        '--list_devices',
                        action='store_true',
                        help='Show list of audio devices and exit')
    parser.add_argument('-r',
                        '--retry_interval',
                        type=float,
                        help='Time in seconds between retries on audio errors',
                        default=1.)
    parser.add_argument('-s',
                        '--sample_rate',
                        type=float,
                        help='Audio sampling frequency',
                        default=48000.)
    parser.add_argument('-f',
                        '--frame_size',
                        type=int,
                        help='Audio frame size',
                        default=512)
    args = parser.parse_args()
    if args.list_devices:
        print(sd.query_devices())
        return
    while True:
        try:
            audio_loop(device=args.device,
                       sample_rate=args.sample_rate,
                       frame_size=args.frame_size,
                       timeout=args.retry_interval)
        except (sd.PortAudioError, AudioTimeout):
            logger.exception('Audio error, retrying...')
            sd._terminate()
            time.sleep(args.retry_interval)
            sd._initialize()
예제 #6
0
import matplotlib.pyplot as plt
import sounddevice as sd

sd._initialize()  #no idea if this is needed

fs = 44100  # Sample rates

#Selecting device is needed on windows????
sd.query_devices()
sd.default.device = 10  #specific personal setting
seconds = 5
myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=2)
sd.wait()
sd._terminate()

#Prints left and right input
print(myrecording)

plt.ion()
plt.figure()
plt.plot(myrecording)
plt.xlabel("Sample Index")
plt.ylabel("Amplitude")

plt.title("Waveform")
plt.show()
예제 #7
0
def _sd_terminate():
    if sd._initialized:
        sd._terminate()
        return True
    else:
        return False