Exemple #1
0
def initialize():
    global p, CHUNK, sounds, filelist
    seed(os.urandom(4))

    try:
        #! Initialize filelists
        filelist = glob.glob(
            "/Users/seanwolford/Developer/Projects/Typyst/res/tw/*.wav")

        #! Initialize streams
        for i, f in enumerate(filelist):
            state = State.default
            macos = pyaudio.PaMacCoreStreamInfo()
            wavfile = wave.open(f, "rb")
            stream = p.open(format=p.get_format_from_width(
                wavfile.getsampwidth()),
                            channels=wavfile.getnchannels(),
                            rate=wavfile.getframerate(),
                            input=False,
                            output=True,
                            frames_per_buffer=CHUNK,
                            output_host_api_specific_stream_info=macos)
            sounds[i] = (wavfile, stream, state)

    except IOError as ioe:
        print("IOError: {0}".format(ioe))
    except EOFError as eof:
        print("EOFError: {0}".format(eof))

    #! Register the signal handlers
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    return
Exemple #2
0
    def setup(self):
        """Set up the speaker for speaking...?"""
        p = self._p
        if self.use_speaker == "left":
            stream_info = pyaudio.PaMacCoreStreamInfo(channel_map=(0, -1))
        elif self.use_speaker == "right":
            stream_info = pyaudio.PaMacCoreStreamInfo(channel_map=(-1, 0))
        else:
            stream_info = pyaudio.PaMacCoreStreamInfo(channel_map=(0, 0))

        self.stream = p.open(
            format=p.get_format_from_width(self.sample_width),
            channels=CHANNELS,
            rate=self.rate,
            input=False,
            output_host_api_specific_stream_info=stream_info,
            output=True,
        )
# left channel audio --> left speaker; no right channel
# channel_map = (0, -1)

# right channel audio --> right speaker; no left channel
# channel_map = (-1, 1)

# left channel audio --> right speaker
# channel_map = (-1, 0)

# right channel audio --> left speaker
channel_map = (1, -1)
# etc...

try:
    stream_info = pyaudio.PaMacCoreStreamInfo(
        flags=pyaudio.PaMacCoreStreamInfo.paMacCorePlayNice,  # default
        channel_map=channel_map)
except AttributeError:
    print("Sorry, couldn't find PaMacCoreStreamInfo. Make sure that "
          "you're running on Mac OS X.")
    sys.exit(-1)

print("Stream Info Flags:", stream_info.get_flags())
print("Stream Info Channel Map:", stream_info.get_channel_map())

# open stream
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                channels=wf.getnchannels(),
                rate=wf.getframerate(),
                output=True,
                output_host_api_specific_stream_info=stream_info)
Exemple #4
0
    def open_stream(self):
        # instantiate PyAudio
        self.p_audio = pyaudio.PyAudio()
        if self.stream_mode == StreamMode.StreamFromFileToFile:
            print colorize("Opening file stream...", COLORS.WARNING)
            # file to file
            format, channels, rate = self.p_audio.get_format_from_width(self.file_source.getsampwidth()), \
                                     self.file_source.getnchannels(), self.file_source.getframerate()
            input_dev_idx = gs_device_info.detect_build_in_input_device_idx(
                self.p_audio)
            output_dev_idx = gs_device_info.detect_build_in_output_device_idx(
                self.p_audio)
            enable_input, enable_output = False, True
        elif self.stream_mode == StreamMode.StreamFromBuildInInputToSoundFlower:
            print colorize("Opening stream...", COLORS.OKBLUE)
            # build-in input to sound flower
            format, channels, rate = FORMAT, CHANNELS, RATE
            input_dev_idx = gs_device_info.detect_build_in_input_device_idx(
                self.p_audio)
            output_dev_idx = gs_device_info.detect_virtual_audio_device_idx(
                self.p_audio)
            enable_input, enable_output = True, True
        elif self.stream_mode == StreamMode.StreamFromSoundFlowerToBuildInOutput:
            print colorize("Opening stream...", COLORS.OKGREEN)
            # sound flower to build-in output
            format, channels, rate = FORMAT, CHANNELS, RATE
            input_dev_idx = gs_device_info.detect_virtual_audio_device_idx(
                self.p_audio)
            output_dev_idx = gs_device_info.detect_build_in_output_device_idx(
                self.p_audio)
            enable_input, enable_output = True, True
        else:
            print colorize("Unsupported stream mode! [%i]" % self.stream_mode,
                           COLORS.FAIL)
            raise ValueError("Unsupported stream mode! [%i]" %
                             self.stream_mode)

        settings = StegoSettings.Instance()

        print colorize("Input device: %i" % input_dev_idx, COLORS.WARNING)
        print colorize("Output device: %i" % output_dev_idx, COLORS.WARNING)
        print colorize(
            "Format: {0}, Channels: {1}, Rate: {2}, Frame size: {3}".format(
                format, channels, rate, settings.frame_size), COLORS.WARNING)
        # standard L-R stereo
        channel_map = (0, 1)
        try:
            stream_info = pyaudio.PaMacCoreStreamInfo(
                flags=pyaudio.PaMacCoreStreamInfo.paMacCorePlayNice,  # default
                channel_map=channel_map)
        except AttributeError:
            print colorize(
                "Sorry, couldn't find PaMacCoreStreamInfo. Make sure that "
                "you're running on OS X.", COLORS.FAIL)
            sys.exit(-1)

        if gs_device_info.validate_audio_setup(self.p_audio, format, channels,
                                               rate, input_dev_idx):
            self.stream = self.p_audio.open(
                format=format,
                channels=channels,
                rate=rate,
                frames_per_buffer=settings.frame_size,
                input=enable_input,
                output=enable_output,
                output_host_api_specific_stream_info=stream_info,
                input_device_index=input_dev_idx,
                output_device_index=output_dev_idx,
                stream_callback=self.__recording_callback)
            self.stream.start_stream()

            src_latency = 1000.0 * self.stream.get_input_latency()
            buffer_latency = 1000.0 * settings.frame_size / rate
            dst_latency = 1000.0 * self.stream.get_output_latency()
            total_latency = buffer_latency + dst_latency + src_latency
            print colorize(
                "Expected delay: %0.1f ms (src: %0.1f, buf: %0.1f, dst: %0.1f)"
                % (total_latency, src_latency, buffer_latency, dst_latency),
                COLORS.WARNING)
        else:
            print colorize("Unsupported audio configuration!", COLORS.FAIL)
            raise ValueError("Unsupported audio configuration!")
    def open_stream(self):
        self.p_audio = pyaudio.PyAudio()
        stream_mode = self.stream_mode
        if stream_mode == StreamMode.BuildInIn2Out:
            # (build-in input) -> [process] -> (build-in output)
            print "Opening (build-in input) -> [process] -> (build-in output) stream..."
            input_dev_idx = self.settings.detect_build_in_input_device_idx(
                self.p_audio)
            output_dev_idx = self.settings.detect_build_in_output_device_idx(
                self.p_audio)
            enable_input, enable_output = True, True
        elif stream_mode == StreamMode.BuildInIn2VD:
            # (build-in input) -> [process] -> (virtual device output)
            print "Opening (build-in input) -> [process] -> (virtual device output) stream..."
            input_dev_idx = self.settings.detect_build_in_input_device_idx(
                self.p_audio)
            output_dev_idx = self.settings.detect_virtual_audio_device_idx(
                self.p_audio)
            enable_input, enable_output = True, True
        elif stream_mode == StreamMode.VD2BuildInOut:
            # (virtual device input) -> [process] -> (build-in output)
            print "Opening (virtual device input) -> [process] -> (build-in output) stream..."
            input_dev_idx = self.settings.detect_virtual_audio_device_idx(
                self.p_audio)
            output_dev_idx = self.settings.detect_build_in_output_device_idx(
                self.p_audio)
            enable_input, enable_output = True, True
        elif stream_mode == StreamMode.File2File:
            # (file) -> [process] -> (file)
            print "Opening (file) -> [process] -> (file) stream..."
            input_dev_idx = self.settings.detect_build_in_input_device_idx(
                self.p_audio)
            output_dev_idx = self.settings.detect_build_in_output_device_idx(
                self.p_audio)
            enable_input, enable_output = True, False
        elif stream_mode == StreamMode.BuildInIn2File:
            # (build-in input) -> [process] -> (file)
            print "Opening (build-in input) -> [process] -> (file) stream..."
            input_dev_idx = self.settings.detect_build_in_input_device_idx(
                self.p_audio)
            output_dev_idx = self.settings.detect_build_in_output_device_idx(
                self.p_audio)
            enable_input, enable_output = True, False
        elif stream_mode == StreamMode.File2BuildInOut:
            # (file) -> [process] -> (build-in output)
            print "Opening (file) -> [process] -> (build-in output) stream..."
            input_dev_idx = self.settings.detect_build_in_input_device_idx(
                self.p_audio)
            output_dev_idx = self.settings.detect_build_in_output_device_idx(
                self.p_audio)
            enable_input, enable_output = False, True
        elif stream_mode == StreamMode.BuildInIn2File:
            # (virtual device input) -> [process] -> (file)
            print "Opening (virtual device input) -> [process] -> (file) stream..."
            input_dev_idx = self.settings.detect_virtual_audio_device_idx(
                self.p_audio)
            output_dev_idx = self.settings.detect_build_in_output_device_idx(
                self.p_audio)
            enable_input, enable_output = True, False
        elif stream_mode == StreamMode.File2BuildInOut:
            # (file) -> [process] -> (virtual device output)
            print "Opening (file) -> [process] -> (virtual device output) stream..."
            input_dev_idx = self.settings.detect_build_in_input_device_idx(
                self.p_audio)
            output_dev_idx = self.settings.detect_virtual_audio_device_idx(
                self.p_audio)
            enable_input, enable_output = False, True
        else:
            print "Unsupported stream mode! [{}]".format(stream_mode)
            raise ValueError(
                "Unsupported stream mode! [{}]".format(stream_mode))

        # standard L-R stereo
        channel_map = (0, 1)
        try:
            stream_info = pyaudio.PaMacCoreStreamInfo(
                flags=pyaudio.PaMacCoreStreamInfo.paMacCorePlayNice,  # default
                channel_map=channel_map)
        except AttributeError:
            print "Sorry, couldn't find PaMacCoreStreamInfo. Make sure that you're running on OS X."
            sys.exit(-1)

        if self.settings.validate_audio_setup(self.p_audio, self.format,
                                              self.channels, self.rate,
                                              input_dev_idx):
            self.stream = self.p_audio.open(
                format=self.format,
                channels=self.channels,
                rate=self.rate,
                frames_per_buffer=self.settings.frame_size,
                input=enable_input,
                output=enable_output,
                output_host_api_specific_stream_info=stream_info,
                input_device_index=input_dev_idx,
                output_device_index=output_dev_idx,
                stream_callback=self.__recording_callback)
            self.stream.start_stream()

            self.__print_stat(input_dev_idx, output_dev_idx)
        else:
            print "Unsupported audio configuration!"
            raise ValueError("Unsupported audio configuration!")
Exemple #6
0
    def run(self):
        """ Run experiment
        
        Return type: tuple(BER, SNR)
        BER -- Bit error rate
        SNR -- Signal to noise before recording
        """

        # Read samples
        carrier_fs, carrier_data = wavfile.read(self.carrier)
        noise_fs, noise_data = wavfile.read(self.noise)

        if noise_fs != carrier_fs:
            print "Sorry, noise and carrier sampling rate should be the same"
            sys.exit(-1)

        # Hardware configuration
        channel_map = (0, 1)
        try:
            stream_info = pyaudio.PaMacCoreStreamInfo(
                flags=pyaudio.PaMacCoreStreamInfo.paMacCorePlayNice, # default
                channel_map=channel_map)
        except AttributeError:
            print("Sorry, couldn't find PaMacCoreStreamInfo. Make sure that "
                    "you're running on Mac OS X.")
            sys.exit(-1)

        # Convert to float32 format
        carrier_data = np.array(carrier_data, dtype=np.float32)
        noise_data = np.array(noise_data, dtype=np.float32)

        # start emitter
        sample_rate = carrier_fs
        sync_frequency = 8800.0
        carrier_frequencies = [ 8003.3, 8105.2, 8209.7, 8318.0, 8399.4, 8521.1, 8587.1, 8691.6 ]
        out = Queue()
        emitter = em.Emitter(carrier_data, sample_rate, sync_frequency, carrier_frequencies, self.payload)
        emitter.outstream(out)
        carrier_data = np.array([], dtype=np.float32)
        while True:
          bts = out.get(True)
          if bts == False:
            break
          carrier_data = np.append(carrier_data, bts)
        carrier_data = np.array(carrier_data, dtype=np.float32)

        print "signal synthesized {0}".format(len(carrier_data))
        # end emitter

        # Normalization
        carrier_data /= max(carrier_data)
        noise_data /= max(noise_data)

        # Mix carrier with noise
        out_data = self._mix(carrier_data, noise_data, self.carrier_mag, self.noise_mag)
        
        # Insert second of silence in beginning
        out_data = np.append(np.zeros(carrier_fs*2, dtype=np.float32), out_data)

        # Init pyaudio object
        pa = pyaudio.PyAudio()

        # Stream to play audio
        out_stream = pa.open(format = pyaudio.paFloat32,
                channels = 2,
                rate = carrier_fs,
                output = True,
                stream_callback = self._output_callback(out_data),
                output_host_api_specific_stream_info = stream_info,
                frames_per_buffer=10000,
                output_device_index = 2)

        print "im sleeping"
        time.sleep(1)
        print "waking up"

        print "playing..."
        
        def in_callback(in_data, frames_count, time_info, status):
            in_callback.recorded_string += in_data
            return (None, pyaudio.paContinue)
        in_callback.recorded_string = ""

        # Stream to record audio
        in_stream = pa.open(format = pyaudio.paFloat32,
                channels = 1,
                rate = carrier_fs,
                input_device_index = 2,
                frames_per_buffer=10000,
                stream_callback = in_callback,
                input = True)

        # Recording
        out_stream.start_stream() # Start playing
        in_stream.start_stream()

        record_padding = 8
        while(out_stream.is_active() or record_padding > 0):
            time.sleep(0.1)
            if not out_stream.is_active():
                record_padding -= 1

        time.sleep(1)

        print "recorded"

        # Stop recording stream
        in_stream.stop_stream()
        in_stream.close()
        
        recorded_data = np.fromstring(in_callback.recorded_string, dtype=np.float32)

        # Stop playing stream
        out_stream.stop_stream()
        out_stream.close()

        # Preview recorded audio
        # out_stream = pa.open(format = pyaudio.paFloat32,
        #         channels = 1,
        #         rate = carrier_fs,
        #         output = True,
        #         stream_callback = self._output_callback(recorded_data, channels = 1),
        #         output_host_api_specific_stream_info = stream_info,
        #         frames_per_buffer=self.blocksize,
        #         output_device_index = 2)

        # while(out_stream.is_active()):
        #     time.sleep(0.1)

        # out_stream.stop_stream()
        # out_stream.close()

        print "recorded {0} samples".format(len(recorded_data))
        rec = Queue()
        out = Queue()
        rec.put(recorded_data.tolist())
        rec.put(False)
        receiver = rc.Receiver(rec, carrier_fs, sync_frequency, carrier_frequencies)
        receiver.payload_stream(out)

        decoded = []
        while True:
          byte = out.get(True)
          if byte == False:
            break
          decoded.append(byte)
        char_payload = [ chr(byte) if 32 <= byte <=126 else '.' for byte in decoded ]
        print "decoded payload: " + "".join(char_payload)

        with open('experiment_ouptut.txt', 'a') as output:
            output.write("experiments.append('{0}', '{1}', '{2}', '{3}', [{4}], [{5}])\n".format(
                self.carrier,
                self.carrier_db,
                self.noise,
                self.noise_db,
                self.payload,
                ",".join(np.array(decoded, dtype=np.str))
            ))

        pa.terminate()

        return decoded
Exemple #7
0
def channelMap():
    chunk = 1024

    PyAudio = pyaudio.PyAudio

    if len(sys.argv) < 2:
        print("Plays a wave file.\n\nUsage: %s output.wav" % sys.argv[0])
        sys.exit(-1)

    wf = wave.open(sys.argv[1], 'rb')

    p = PyAudio()

    # standard L-R stereo
    # channel_map = (0, 1)

    # reverse: R-L stereo
    # channel_map = (1, 0)

    # no audio
    # channel_map = (-1, -1)

    # left channel audio --> left speaker; no right channel
    # channel_map = (0, -1)

    # right channel audio --> right speaker; no left channel
    # channel_map = (-1, 1)

    # left channel audio --> right speaker
    # channel_map = (-1, 0)

    # right channel audio --> left speaker
    channel_map = (1, -1)
    # etc...

    try:
        stream_info = pyaudio.PaMacCoreStreamInfo(
            flags=pyaudio.PaMacCoreStreamInfo.paMacCorePlayNice, # default
            channel_map=channel_map)
    except AttributeError:
        print("Sorry, couldn't find PaMacCoreStreamInfo. Make sure that "
              "you're running on Mac OS X.")
        sys.exit(-1)

    print("Stream Info Flags:", stream_info.get_flags())
    print("Stream Info Channel Map:", stream_info.get_channel_map())

    # open stream
    stream = p.open(
        format=p.get_format_from_width(wf.getsampwidth()),
        channels=wf.getnchannels(),
        rate=wf.getframerate(),
        output=True,
        output_host_api_specific_stream_info=stream_info)

    # read data
    data = wf.readframes(chunk)

    # play stream
    while data != '':
        stream.write(data)
        data = wf.readframes(chunk)

    stream.stop_stream()
    stream.close()

    p.terminate()