Python sounddevice.play() Examples

The following are 19 code examples of sounddevice.play(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sounddevice , or try the search function .
Example #1
Source File: bss_example.py    From pyroomacoustics with MIT License 6 votes vote down vote up
def __init__(self, master, fs, mix, sources):
                self.master = master
                self.fs = fs
                self.mix = mix
                self.sources = sources
                master.title("A simple GUI")

                self.label = Label(master, text="This is our first GUI!")
                self.label.pack()

                self.mix_button = Button(master, text='Mix', command=lambda: self.play(self.mix))
                self.mix_button.pack()

                self.buttons = []
                for i, source in enumerate(self.sources):
                    self.buttons.append(Button(master, text='Source ' + str(i+1), command=lambda src=source : self.play(src)))
                    self.buttons[-1].pack()

                self.stop_button = Button(master, text="Stop", command=sd.stop)
                self.stop_button.pack()

                self.close_button = Button(master, text="Close", command=master.quit)
                self.close_button.pack() 
Example #2
Source File: MorseDecoder.py    From LSTM_morse with MIT License 6 votes vote down vote up
def audio(self):
        """Generate audio file using other functions"""
        self.morsecode = []
        self.pad_start()
        self.generate_audio()
        self.pad_end()
        self.SNR()
        self.normalize()
        if self.play_sound:
            sd.play(self.morsecode, self.Fs)
        if self.file_name:
            write(self.file_name, self.Fs, self.morsecode)
        return self.morsecode 
Example #3
Source File: MorseDecoder.py    From LSTM_morse with MIT License 6 votes vote down vote up
def __init__(self, text, file_name=None, SNR_dB=20, f_code=600, Fs=8000, code_speed=20, length_seconds=4, total_seconds=8, play_sound=True):
        self.text = text.upper()              # store requested text to be converted in here 
        self.file_name = file_name            # file name to store generated WAV file 
        self.SNR_dB = SNR_dB                  # target SNR in dB 
        self.f_code = f_code                  # CW tone frequency
        self.Fs = Fs                          # Sampling frequency 
        self.code_speed = code_speed          # code speed in WPM
        self.length_seconds = length_seconds  # caps the CW generation to this length in seconds
        self.total_seconds = total_seconds    # pads to the total length if possible 
        self.play_sound = play_sound          # If true, play the generated audio 

        self.len = self.len_str_in_dits(self.text)
        self.morsecode = []  # store audio representation here 
        self.t = np.linspace(0., 1.2/self.code_speed, num=int(self.Fs*1.2/self.code_speed), endpoint=True, retstep=False)
        self.Dit = np.sin(2*np.pi*self.f_code*self.t)
        self.ssp = np.zeros(len(self.Dit))
        # one Dah of time is 3 times  dit time
        self.t2 = np.linspace(0., 3*1.2/self.code_speed, num=3*int(self.Fs*1.2/self.code_speed), endpoint=True, retstep=False)
        self.Dah = np.sin(2*np.pi*self.f_code*self.t2)
        self.lsp = np.zeros(len(self.Dah)) 
Example #4
Source File: generate.py    From LSTM_morse with MIT License 6 votes vote down vote up
def __init__(self, text, file_name=None, SNR_dB=20, f_code=600, Fs=8000, code_speed=20, length_seconds=4, total_seconds=8, play_sound=True):
        self.text = text.upper()              # store requested text to be converted in here 
        self.file_name = file_name            # file name to store generated WAV file 
        self.SNR_dB = SNR_dB                  # target SNR in dB 
        self.f_code = f_code                  # CW tone frequency
        self.Fs = Fs                          # Sampling frequency 
        self.code_speed = code_speed          # code speed in WPM
        self.length_seconds = length_seconds  # caps the CW generation to this length in seconds
        self.total_seconds = total_seconds    # pads to the total length if possible 
        self.play_sound = play_sound          # If true, play the generated audio 

        self.len = self.len_str_in_dits(self.text)
        self.morsecode = []  # store audio representation here 
        self.t = np.linspace(0., 1.2/self.code_speed, num=int(self.Fs*1.2/self.code_speed), endpoint=True, retstep=False)
        self.Dit = np.sin(2*np.pi*self.f_code*self.t)
        self.ssp = np.zeros(len(self.Dit))
        # one Dah of time is 3 times  dit time
        self.t2 = np.linspace(0., 3*1.2/self.code_speed, num=3*int(self.Fs*1.2/self.code_speed), endpoint=True, retstep=False)
        #Dah = np.concatenate((Dit,Dit,Dit))
        self.Dah = np.sin(2*np.pi*self.f_code*self.t2)
        self.lsp = np.zeros(len(self.Dah)) 
Example #5
Source File: timit.py    From pyroomacoustics with MIT License 5 votes vote down vote up
def play(self):
        ''' Play the sound sample '''
        if have_sounddevice:
            sd.play(self.data, samplerate=self.fs)
        else:
            print('Warning: sounddevice package is required to play audiofiles.') 
Example #6
Source File: routines.py    From overiva with MIT License 5 votes vote down vote up
def play(self, src):
        sd.play(0.75 * src / self.sources_max, samplerate=self.fs, blocking=False) 
Example #7
Source File: speech_utils.py    From python-dlpy with Apache License 2.0 5 votes vote down vote up
def play_one_audio_file(local_audio_file):
    '''
    Play a local audio file using soundfile and sounddevice.

    Parameters
    ----------
    local_audio_file : string
        Local location to the audio file to be played. When it is a directory,
        a file will be randomly chosen.

    Returns
    -------
    None

    Raises
    ------
    DLPyError
        If anything goes wrong, it complains and prints the appropriate message.

    '''

    try:
        import soundfile as sf
        import sounddevice as sd
    except (ModuleNotFoundError, ImportError):
        raise DLPyError('cannot import soundfile or sounddevice')

    if os.path.isdir(local_audio_file):
        local_audio_file_real = random_file_from_dir(local_audio_file)
    else:
        local_audio_file_real = local_audio_file

    print('File location: {}'.format(local_audio_file_real))

    data, sampling_rate = sf.read(local_audio_file_real)

    print('Frequency [Hz]: {}'.format(sampling_rate))
    print('Duration [s]: {}'.format(data.shape[0]/sampling_rate))
    sd.play(data, sampling_rate)
    sd.wait() 
Example #8
Source File: demo_utils.py    From Resemblyzer with Apache License 2.0 5 votes vote down vote up
def play_wav(wav, blocking=True):
    try:
        import sounddevice as sd
        # Small bug with sounddevice.play: the audio is cut 0.5 second too early. We pad it to 
        # make up for that
        wav = np.concatenate((wav, np.zeros(sampling_rate // 2)))
        sd.play(wav, sampling_rate, blocking=blocking)
    except Exception as e:
        print("Failed to play audio: %s" % repr(e)) 
Example #9
Source File: generate.py    From LSTM_morse with MIT License 5 votes vote down vote up
def audio(self):
        """Generate audio file using other functions"""
        self.morsecode = []
        self.pad_start()
        self.generate_audio()
        self.pad_end()
        self.SNR()
        self.normalize()
        if self.play_sound:
            sd.play(self.morsecode, self.Fs)
        if self.file_name:
            write(self.file_name, self.Fs, self.morsecode) 
Example #10
Source File: SpeechOutputPlayer.py    From adviser with GNU General Public License v3.0 5 votes vote down vote up
def speak(self, system_speech):
        """
        Takes the system utterance and reads it out. Also can log the audio and text.
        
        Args:
            system_speech (np.array): An array of audio that is meant to produce a sound from. The result of the systems TTS synthesis service.
        """
        sounddevice.play(system_speech[0], system_speech[1])

        # log the utterance
        if self.conversation_log_dir is not None:
            file_path = os.path.join(self.conversation_log_dir, (str(math.floor(time.time()))))
            librosa.output.write_wav(file_path + "_system.wav", system_speech[0], system_speech[1])
            with open(file_path + "_system.txt", "w") as convo_log:
                convo_log.write(system_speech[2]) 
Example #11
Source File: sound.py    From morse-talk with GNU General Public License v2.0 5 votes vote down vote up
def preview_wave(message, wpm=WPM, frequency=FREQUENCY, framerate=FRAMERATE, amplitude=AMPLITUDE, word_ref=WORD):
    """
    Listen (preview) wave

    sounddevice is required http://python-sounddevice.readthedocs.org/
    $ pip install sounddevice
    """
    samp_nb = samples_nb(message=message, wpm=wpm, framerate=framerate, word_spaced=False)
    import sounddevice as sd
    lst_bin = _encode_binary(message)
    amplitude = _limit_value(amplitude)
    seconds_per_dot = _seconds_per_dot(word_ref)  # 1.2
    a = [calculate_wave(i, lst_bin, wpm, frequency, framerate, amplitude, seconds_per_dot)
         for i in range(samp_nb)]
    sd.play(a, framerate, blocking=True) 
Example #12
Source File: timit.py    From pyroomacoustics with MIT License 5 votes vote down vote up
def play(self):
        ''' Play the sound sample '''
        if have_sounddevice:
            sd.play(self.samples, samplerate=self.fs)
        else:
            print('Warning: sounddevice package is required to play audiofiles.') 
Example #13
Source File: test_trinicon.py    From pyroomacoustics with MIT License 5 votes vote down vote up
def play(ch):
        sd.play(pra.normalize(y[ch]) * 0.75, samplerate=room.fs, blocking=True) 
Example #14
Source File: bss_live.py    From pyroomacoustics with MIT License 5 votes vote down vote up
def play(self, src):
            sd.play(pra.normalize(src) * 0.75, samplerate=self.fs, blocking=False) 
Example #15
Source File: bss_live.py    From pyroomacoustics with MIT License 5 votes vote down vote up
def __init__(self, master, fs, mix, sources):
            self.master = master
            self.fs = fs
            self.mix = mix
            self.sources = sources
            master.title("A simple GUI")

            self.label = Label(master, text="This is our first GUI!")
            self.label.pack()

            self.mix_button = Button(
                master, text="Mix", command=lambda: self.play(self.mix)
            )
            self.mix_button.pack()

            self.buttons = []
            for i, source in enumerate(self.sources):
                self.buttons.append(
                    Button(
                        master,
                        text="Source " + str(i + 1),
                        command=lambda src=source: self.play(src),
                    )
                )
                self.buttons[-1].pack()

            self.stop_button = Button(master, text="Stop", command=sd.stop)
            self.stop_button.pack()

            self.close_button = Button(master, text="Close", command=master.quit)
            self.close_button.pack() 
Example #16
Source File: bss_example.py    From pyroomacoustics with MIT License 5 votes vote down vote up
def play(self, src):
                sd.play(pra.normalize(src) * 0.75, samplerate=self.fs, blocking=False) 
Example #17
Source File: soundPlayer.py    From Tickeys-linux with MIT License 5 votes vote down vote up
def play(self, key):
        if not self.key_audio_map.get(str(key)):
            self.key_audio_map[str(key)] = key % self.non_unique_count
        data, fs = self.sound_effect_cache[self.key_audio_map[str(key)]]
        data = data * self.configer.volume
        fs = fs * self.configer.pitch
        threading.Thread(target=sd.play, args=(data, fs)).start() 
Example #18
Source File: sounddeviceplayer.py    From kalliope with GNU General Public License v3.0 5 votes vote down vote up
def play(self, file_path):

        if self.convert:
            self.convert_mp3_to_wav(file_path_mp3=file_path)
        data, fs = sf.read(file_path)
        sd.play(data, fs)
        sd.wait() 
Example #19
Source File: routines.py    From overiva with MIT License 4 votes vote down vote up
def __init__(self, master, fs, mix, sources, references=None):
        self.master = master
        self.fs = fs
        self.mix = mix
        self.sources = sources
        self.sources_max = np.max(np.abs(sources))
        self.references = references.copy()
        master.title("Comparator")

        if self.references is not None:
            self.references *= 0.75 / np.max(np.abs(self.references))

        nrow = 0

        self.label = Label(master, text="Listen to the output.")
        self.label.grid(row=nrow, columnspan=2)
        nrow += 1

        self.mix_button = Button(
            master, text="Mix", command=lambda: self.play(self.mix)
        )
        self.mix_button.grid(row=nrow, columnspan=2)
        nrow += 1

        self.buttons = []
        for i, source in enumerate(self.sources):
            self.buttons.append(
                Button(
                    master,
                    text="Source " + str(i + 1),
                    command=lambda src=source: self.play(src),
                )
            )

            if self.references is not None:
                self.buttons[-1].grid(row=nrow, column=1)
                ref_sig = self.references[i, :]
                self.buttons.append(
                    Button(
                        master,
                        text="Ref " + str(i + 1),
                        command=lambda rs=self.references[i, :]: self.play(rs),
                    )
                )
                self.buttons[-1].grid(row=nrow, column=0)

            else:
                self.buttons[-1].grid(row=nrow, columnspan=2)

            nrow += 1

        self.stop_button = Button(master, text="Stop", command=sd.stop)
        self.stop_button.grid(row=nrow, columnspan=2)
        nrow += 1

        self.close_button = Button(master, text="Close", command=master.quit)
        self.close_button.grid(row=nrow, columnspan=2)
        nrow += 1