Exemplo n.º 1
0
class MicFilter:
    def __init__(self):
        self.micIO = MicIO()
        self.noise_clip = None

    @staticmethod
    def bandpass(data, fs, lowf, highf, order):
        nyq = 0.5 * fs
        lowf /= nyq
        highf /= nyq
        num, den = butter(order, [lowf, highf], btype='band')
        filtered = lfilter(num, den, data)
        return filtered

    def record_noise(self, data):
        noise = np.frombuffer(data, dtype=np.int16)
        self.noise_clip = np.append(self.noise_clip, noise)

    def calibrate_noise(self, seconds, device_id=None):
        self.noise_clip = np.array([])
        self.micIO.listen(self.record_noise, device_index=device_id)
        time.sleep(seconds)
        self.micIO.stop()

    def remove_noise(self, audio_clip):
        if self.noise_clip.size == 0:
            print('Error: must calibrate noise levels before removing noise')
            return None
        return nr.reduce_noise(audio_clip=audio_clip, noise_clip=self.noise_clip)

    def trim_beginning_silence(self, audio_clip, fs=MicIO.SamplingFrequency, rms_window_ms=10):
        rms_window = rms_window_ms * (fs // 1000)
        if len(audio_clip) <= rms_window:
            print('Input audio should be longer than %d ms' % rms_window_ms)
            return None

        safety_factor = 1.5
        noise_rms = np.sqrt(np.mean(self.noise_clip**2)) * safety_factor

        audio_clip_squared = audio_clip ** 2

        index = 0
        current_sum = np.sum(audio_clip_squared[index:index+rms_window])
        rms = np.sqrt(current_sum/rms_window)
        index += 1

        while rms < noise_rms and index < audio_clip_squared.size:
            current_sum -= audio_clip_squared[index-1]
            current_sum += audio_clip_squared[index]
            rms = np.sqrt(current_sum/rms_window)
            index += 1

        if index == audio_clip_squared.size:
            print('Trim: did not find any beginning silence')
            return audio_clip

        return audio_clip[index:]
Exemplo n.º 2
0
class MicTransmitter:
    def __init__(self):
        self.micIO = MicIO()
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def callback(self, data):
        self.socket.sendall(data)

    def start(self, host, port, device_index=None):
        try:
            self.socket.connect((host, port))
        except:
            return False
        self.micIO.listen(self.callback, device_index)
        return True

    def stop(self):
        self.socket.close()
        self.micIO.stop()
Exemplo n.º 3
0
 def __init__(self):
     self.micIO = MicIO()
     self.noise_clip = None
Exemplo n.º 4
0
from MicIO import MicIO
import sys

micIO = MicIO()

try:
    again = 'y'
    while again == 'y':
        micIO.play(sys.argv[1], device_index=None)
        again = input('Play again? (y/n) ')
except KeyboardInterrupt:
    print('')

micIO.terminate()
Exemplo n.º 5
0
def main():
    custom_formatter = lambda prog: argparse.RawTextHelpFormatter(
        prog, max_help_position=100)
    p = argparse.ArgumentParser(formatter_class=custom_formatter)

    p.add_argument('--internal-mic', action='store_true', required=False)
    p.add_argument('--noise-cal', type=int, required=False)
    p.add_argument('--filter-specs', type=str, required=False)
    args = p.parse_args()

    device_id = None
    noise_cal_s = 1
    output_wav = 'MicLoopback.wav'
    output_wav_filtered = '%s-filtered.wav' % output_wav.split('.')[0]
    filter_specs = FILTER_SPECS

    if not args.internal_mic:
        micIO = MicIO()
        for i in range(micIO.pyaudio_io.get_device_count()):
            dev = micIO.pyaudio_io.get_device_info_by_index(i)
            if dev['name'] == PNP_MIC and dev[
                    'maxInputChannels'] == PNP_MIC_MAX_INPUT_CHANNELS:
                device_id = i
        if device_id:
            print('Using external mic: %s' % PNP_MIC)
        else:
            print('Could not find external mic: %s' % PNP_MIC)
            return

    if args.noise_cal:
        noise_calibration_s = args.noise_cal

    if args.filter_specs:
        filter_specs = args.filter_specs

    filter_specs = list(map(int, filter_specs.split(',')))
    if len(filter_specs) is not 3:
        print(
            "Must specify filter specs with LOW,HIGH,ORDER -- e.g. -f 100,12000,3"
        )
        return
    filter_lowf = filter_specs[0]
    filter_highf = filter_specs[1]
    filter_order = filter_specs[2]
    print('Filter specs: {0}hz-{1}hz, order={2}'.format(
        filter_lowf, filter_highf, filter_order))

    micIO = MicIO()
    micFilter = MicFilter()

    input('Press any key to begin calibrating noise levels for %d second(s)' %
          noise_cal_s)
    micFilter.calibrate_noise(seconds=noise_cal_s, device_id=device_id)
    print('Noise calibration finished')

    try:
        while True:
            recording.clear()

            input('Press any key to begin recording')
            micIO.listen(record, device_id)

            input('Recording... press any key to stop recording')
            micIO.stop()

            audio_unfiltered = np.array(recording)
            audio_unfiltered = audio_unfiltered.astype(np.int16)
            micIO.save(output_wav, audio_unfiltered)
            print('Saved raw recording to %s' % output_wav)

            audio_filtered = MicFilter.bandpass(recording,
                                                fs=MicIO.SamplingFrequency,
                                                lowf=filter_specs[0],
                                                highf=filter_specs[1],
                                                order=filter_specs[2])
            audio_filtered = micFilter.trim_beginning_silence(
                audio_clip=audio_filtered)
            audio_filtered = micFilter.remove_noise(audio_filtered)
            audio_filtered = audio_filtered.astype(np.int16)
            micIO.save(output_wav_filtered, audio_filtered)
            print('Saved filtered recording to %s' % output_wav_filtered)

            cmd = input('Playback? (raw/filtered/no) ')

            while cmd == 'raw' or cmd == 'r' or cmd == 'filtered' or cmd == 'f':
                if cmd == 'filtered' or cmd == 'f':
                    micIO.play(output_wav_filtered)
                else:
                    micIO.play(output_wav)
                cmd = input('Playback? (raw/filtered/no) ')

    except KeyboardInterrupt:
        print('\n')
        pass
Exemplo n.º 6
0
 def __init__(self):
     self.micIO = MicIO()
     self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)