SoundStimulus class#

The SoundStimulus class holds an auditory stimulus.

class thebeat.core.SoundStimulus(samples, fs, name=None)[source]#

A SoundStimulus object holds a sound.

You can use the different class methods to generate a sound, to get a sound from a .wav file, or to import a parselmouth.Sound object. This SoundStimulus sound is used when generating a trial with the SoundSequence class. Additionally, one can plot the object, change the amplitude, etc.

__init__(samples, fs, name=None)[source]#

The constructor for the SoundStimulus class. Except for special cases, this is only used internally. You’ll most likely want to use one of the different class methods to construct a SoundStimulus object, such as SoundStimulus.generate() or SoundStimulus.from_wav().

Both mono and stereo sounds are supported.

Notes

For more information on how these samples are created, see the SciPy documentation.

Parameters:
  • samples (ndarray) – An array containing the audio samples with frequency fs.

  • fs (int) – The sampling frequency.

  • name (Optional[str], default: None) – Optionally, the SoundStimulus object can have a name. This is saved to the SoundStimulus.name attribute.

change_amplitude(factor)[source]#

This method can be used to change the amplitude of the SoundStimulus sound. A factor between 0 and 1 decreases the amplitude; a factor larger than 1 increases the amplitude.

Parameters:

factor (float) – The factor by which the sound should be amplified.

Examples

>>> sound = SoundStimulus.generate()
>>> sound.change_amplitude(factor=0.5)  # half as loud
>>> sound.change_amplitude(factor=2)  # twice as loud
copy(deep=True)[source]#

Returns a copy of itself. See copy.copy() for more information.

Parameters:

deep (bool, default: True) – If True, a deep copy is returned. If False, a shallow copy is returned.

property duration_ms: float64#

The duration of the SoundStimulus sound in milliseconds.

property duration_s: float64#

The duration of the SoundStimulus sound in seconds.

classmethod from_note(note_str, duration=50, fs=48000, amplitude=1.0, oscillator='sine', onramp_ms=0, offramp_ms=0, ramp='linear', name=None)[source]#

Generate a SoundStimulus object on the basis of a note as a string. For instance, a note_str of 'G4' results in a generated SoundStimulus with a pitch frequency of 392 hertz.

Parameters:
  • note_str (str) – A note as a string. Can either be provided as 'G' or 'G4'.

  • duration (int, default: 50) – The duration in milliseconds.

  • fs (int, default: 48000) – The sampling frequency in hertz.

  • amplitude (float, default: 1.0) – Factor with which sound is amplified. Values between 0 and 1 result in sounds that are less loud, values higher than 1 in louder sounds.

  • oscillator (str, default: 'sine') – The oscillator used for generating the sound. Either ‘sine’ (the default), ‘square’ or ‘sawtooth’.

  • onramp_ms (int, default: 0) – The sound’s ‘attack’ in milliseconds.

  • offramp_ms (int, default: 0) – The sound’s ‘decay’ in milliseconds.

  • ramp (str, default: 'linear') – The type of on- and offramp_ms used. Either ‘linear’ (the default) or ‘raised-cosine’.

  • name (Optional[str], default: None) – Optionally, one can provide a name for the SoundStimulus. This is for instance useful when distinguishing A and B stimuli. It is used when the SoundStimulus sound is printed, written to a file, or when it is plotted.

Return type:

SoundStimulus

Examples

>>> stim = SoundStimulus.from_note('G',duration=20)
>>> stim = SoundStimulus.from_note('G4',onramp_ms=10, offramp_ms=10, ramp='raised-cosine')
classmethod from_parselmouth(sound_object, name=None)[source]#

This class method generates a SoundStimulus object from a parselmouth.Sound object.

Parameters:
  • sound_object (parselmouth.Sound object) – The to-be imported Parselmouth Sound object.

  • name (str, optional) – Optionally, one can provide a name for the SoundStimulus. This is for instance useful when distinguishing A and B stimuli. It is used when the SoundStimulus sound is printed, written to a file, or when it is plotted.

Return type:

SoundStimulus

classmethod from_wav(filepath, new_fs=None, name=None)[source]#

This method loads a stimulus from a PCM .wav file, and reads in the samples. If necessary, it additionally converts the dtype to numpy.float64.

The standard behaviour is that the sampling frequency (fs) of the input file is used. If desired, the input file can be resampled using the new_fs parameter.

Parameters:
  • filepath (PathLike | str) – The location of the .wav file. Either pass it e.g. a pathlib.Path object, or a string. Of course be aware of OS-specific filepath conventions.

  • name (Optional[str], default: None) – If desired, one can give a SoundStimulus object a name. This is used, for instance, when plotting or printing. It can always be retrieved from the SoundStimulus.name atrribute.

  • new_fs (Optional[int], default: None) – If resampling is required, you can provide the target sampling frequency here, for instance 48000.

Return type:

SoundStimulus

Examples

>>> from thebeat import SoundStimulus
>>> sound = SoundStimulus.from_wav(filepath="path/to/sound.wav")  
>>> sound_newfs = SoundStimulus.from_wav(filepath="path/to/sound.wav", new_fs=48000)  
classmethod generate(freq=440, fs=48000, duration_ms=50, n_channels=1, amplitude=1.0, oscillator='sine', onramp_ms=0, offramp_ms=0, ramp_type='linear', name=None)[source]#

This class method returns a SoundStimulus object with a generated sound, based on the given parameters. It is recommended to use the on- and offramp parameters for the best results.

Parameters:
  • freq (int, default: 440) – The pitch frequency in hertz.

  • fs (int, default: 48000) – The sampling frequency in hertz.

  • duration_ms (float, default: 50) – The duration in milliseconds.

  • n_channels (int, default: 1) – The number of channels. 1 for mono, 2 for stereo.

  • amplitude (float, default: 1.0) – Factor with which sound is amplified. Values between 0 and 1 result in sounds that are less loud, values higher than 1 in louder sounds.

  • oscillator (str, default: 'sine') – Either ‘sine’ (the default) ‘square’ or ‘sawtooth’.

  • onramp_ms (float, default: 0) – The sound’s ‘attack’ in milliseconds.

  • offramp_ms (float, default: 0) – The sound’s ‘decay’ in milliseconds.

  • ramp_type (str, default: 'linear') – The type of on- and offramp used. Either ‘linear’ (the default) or ‘raised-cosine’.

  • name (Optional[str], default: None) – Optionally, one can provide a name for the SoundStimulus. This is for instance useful when distinguishing A and B stimuli. It is used when the SoundStimulus sound is printed, written to a file, or when it is plotted.

Return type:

SoundStimulus

Examples

>>> stim = SoundStimulus.generate(freq=1000, onramp_ms=10, offramp_ms=10)
>>> stim.plot_waveform()  
classmethod generate_white_noise(duration_ms=50, sigma=1, fs=48000, n_channels=1, amplitude=1.0, rng=None, name=None)[source]#

This class method returns a SoundStimulus object with white noise. They are simply random samples from a normal distribution with mean 0 and standard deviation sd.

Parameters:
  • duration_ms (int, default: 50) – The desired duration in milliseconds.

  • sigma (float, default: 1) – The standard deviation of the normal distribution from which the samples are drawn.

  • fs (int, default: 48000) – The sampling frequency in hertz.

  • n_channels (int, default: 1) – The number of channels. 1 for mono, 2 for stereo.

  • amplitude (float, default: 1.0) – Factor with which sound is amplified. Values between 0 and 1 result in sounds that are less loud, values higher than 1 in louder sounds.

  • rng (Optional[Generator], default: None) – A numpy.random.Generator object. If not supplied numpy.random.default_rng() is used.

  • name (Optional[str], default: None) – Optionally, one can provide a name for the SoundStimulus. This is for instance useful when distinguishing A and B stimuli. It is used when the SoundStimulus sound is printed, written to a file, or when it is plotted.

Return type:

SoundStimulus

Examples

>>> stim = SoundStimulus.generate_white_noise()
>>> stim.plot_waveform()  
merge(other)[source]#

Merge this SoundStimulus object with one or multiple other SoundStimulus objects.

Returns a new SoundStimulus object.

Parameters:

other (SoundStimulus | list[SoundStimulus]) – A SoundStimulus object, or a list of SoundStimulus objects.

Returns:

A SoundStimulus object.

Return type:

object

play(loop=False)[source]#

This method uses sounddevice.play() to play the SoundStimulus sound.

Parameters:

loop (bool, default: False) – If True, the SoundStimulus object is played until the SoundStimulus.stop() method is called.

Return type:

None

Examples

>>> stim = SoundStimulus.generate()
>>> stim.play()  
plot_waveform(**kwargs)[source]#

This method plots the waveform of the SoundStimulus sound.

Parameters:

**kwargs – Additional parameters (e.g. ‘title’, ‘dpi’ are passed to thebeat.helpers.plot_waveform()).

Return type:

tuple[Figure, Axes]

Examples

>>> stim = SoundStimulus.generate()
>>> stim.plot_waveform(title="Waveform of stimulus")  
>>> import matplotlib.pyplot as plt  
>>> stim = SoundStimulus.generate()
>>> fig, ax = stim.plot_waveform(suppress_display=True)
>>> fig.set_facecolor('blue')
>>> plt.show()  
stop()[source]#

Stop playing the SoundStimulus sound. Calls sounddevice.stop().

Return type:

None

Examples

>>> import time  
>>> stim = SoundStimulus.generate()  
>>> stim.play()  
>>> time.sleep(secs=1)  
>>> stim.stop()  
write_wav(filepath, dtype=<class 'numpy.int16'>)[source]#

Save the SoundStimulus sound to disk as a wave file.

Parameters:
  • filepath (str | PathLike) – The output destination for the .wav file. Either pass e.g. a Path object, or a string. Of course be aware of OS-specific filepath conventions.

  • dtype (str | dtype, default: <class 'numpy.int16'>) – The data type of the samples. Defaults to np.int16, meaning that the samples are saved as 16-bit integers.

Return type:

None

Examples

>>> stim = SoundStimulus.generate()
>>> stim.write_wav('my_stimulus.wav')