### PsychoPy Manual Installation - Path Configuration Source: https://parselmouth.readthedocs.io/en/stable/_sources/installation Example of how to configure the path to the Parselmouth library within PsychoPy's General Preferences on Windows and Mac OS X. ```python ['C:/Users/Yannick/parselmouth-psychopy/'] ``` ```python ['/Users/yannick/parselmouth-psychopy/'] ``` -------------------------------- ### Install Parselmouth Source: https://parselmouth.readthedocs.io/en/stable/installation Installs the Parselmouth Python library using pip. This is the primary method for installing the package on Linux, macOS, and Windows. ```Python pip install praat-parselmouth ``` -------------------------------- ### PsychoPy Installation Script Source: https://parselmouth.readthedocs.io/en/stable/installation A Python script that can be run directly within the PsychoPy Coder interface to install Parselmouth. This is an alternative to the manual installation steps, particularly for users who encounter issues with the manual method or prefer a script-based approach. ```Python psychopy_installation.py ``` -------------------------------- ### Install Parselmouth in PsychoPy (Standalone) Source: https://parselmouth.readthedocs.io/en/stable/installation This section details the manual installation process for Parselmouth within standalone PsychoPy versions, which do not support direct pip installations. It involves downloading a specific .whl file, renaming it to .zip, extracting its contents, and updating PsychoPy's preferences to include the path to the extracted library. ```Python import sys; print(sys.version_info) ``` ```Python import platform; print(platform.architecture()[0]) ``` ```Shell import parselmouth ``` -------------------------------- ### Install Parselmouth Source: https://parselmouth.readthedocs.io/en/stable/_sources/installation Installs the Parselmouth Python library using pip. This is the standard method for most Python installations. ```bash pip install praat-parselmouth ``` -------------------------------- ### Update Pip Source: https://parselmouth.readthedocs.io/en/stable/installation Updates the pip package installer to the latest version. A recent version of pip is often required for installing precompiled wheels. ```bash pip install -U pip ``` -------------------------------- ### Install Parselmouth from Python Interpreter Source: https://parselmouth.readthedocs.io/en/stable/installation Installs the praat-parselmouth package directly from within a Python interpreter, automatically using the correct Python executable. Extra arguments for pip can be added to the subprocess call. ```python >>> import sys, subprocess >>> subprocess.call([sys.executable, '-m', 'pip', 'install', 'praat-parselmouth']) ``` -------------------------------- ### Windows DLL Load Error Solution Source: https://parselmouth.readthedocs.io/en/stable/installation Provides links to download the Microsoft Visual C++ Redistributable for Visual Studio 2017/2019, which resolves 'ImportError: DLL load failed' on Windows by providing missing system files. ```url https://aka.ms/vs/16/release/VC_redist.x64.exe ``` ```url https://aka.ms/vs/16/release/VC_redist.x86.exe ``` -------------------------------- ### Install Parselmouth with Specific Python Version Source: https://parselmouth.readthedocs.io/en/stable/installation Installs the praat-parselmouth package using the pip associated with a specific Python installation. This is useful when multiple Python versions are present on the system. ```bash python -m pip install praat-parselmouth ``` -------------------------------- ### Manual PsychoPy Installation Script Source: https://parselmouth.readthedocs.io/en/stable/_sources/installation A Python script to be run within the PsychoPy Coder interface for installing Parselmouth into standalone PsychoPy versions. ```python download "psychopy_installation.py" ``` -------------------------------- ### Upgrade Parselmouth Source: https://parselmouth.readthedocs.io/en/stable/installation Updates an existing installation of the Parselmouth Python library to the latest release using pip. The -U or --upgrade flag ensures the newest version is installed. ```Python pip install -U praat-parselmouth ``` -------------------------------- ### Parselmouth Examples Overview Source: https://parselmouth.readthedocs.io/en/stable/examples Demonstrates the versatility of Parselmouth in various contexts, combining Praat functionality with standard Python features or other Python libraries. The examples cover plotting, batch processing of files, pitch manipulation and Praat commands, PsychoPy experiments, and web services. ```Python # Examples of Parselmouth usage: # - Plotting # - Batch processing of files # - Pitch manipulation and Praat commands # - PsychoPy experiments # - Web service ``` -------------------------------- ### Running Flask Server in a Thread Source: https://parselmouth.readthedocs.io/en/stable/examples/web_service This Python code snippet starts the Flask development server in a separate subprocess. It forwards the server's standard output and standard error to the Jupyter notebook's output, allowing monitoring of the server's status. A short delay is included to ensure the server has time to initialize. ```Python import os import subprocess import sys import time # Start a subprocess that runs the Flask server p = subprocess.Popen([sys.executable, "-m", "flask", "run"], env=dict(**os.environ, FLASK_APP="server.py"), stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Start two subthreads that forward the output from the Flask server to the output of the Jupyter notebook def forward(i, o): while p.poll() is None: l = i.readline().decode('utf-8') if l: o.write("[SERVER] " + l) import threading threading.Thread(target=forward, args=(p.stdout, sys.stdout)).start() threading.Thread(target=forward, args=(p.stderr, sys.stderr)).start() # Let's give the server a bit of time to make sure it has started time.sleep(2) ``` -------------------------------- ### Shell: File Cleanup Source: https://parselmouth.readthedocs.io/en/stable/examples/web_service This command demonstrates how to remove a file from the disk. ```Shell # Cleaning up the file that was written to disk !rm ``` -------------------------------- ### JavaScript/HTML: Web Service Client for Pitch Track Source: https://parselmouth.readthedocs.io/en/stable/examples/web_service This example demonstrates a client-side HTML page with JavaScript that sends an audio file to a Flask web service and plots the returned pitch track using Plotly. It includes form submission and AJAX request handling. ```HTML
``` -------------------------------- ### Creating Output Directory Source: https://parselmouth.readthedocs.io/en/stable/examples/psychopy_experiments Creates a directory to store the generated example output files. This is a preliminary step before saving any generated stimuli. ```bash !mkdir ``` -------------------------------- ### Update Parselmouth Source: https://parselmouth.readthedocs.io/en/stable/_sources/installation Updates an existing Parselmouth installation to the latest available version using pip. ```bash pip install -U praat-parselmouth ``` -------------------------------- ### Install Microsoft Visual C++ Redistributable Source: https://parselmouth.readthedocs.io/en/stable/_sources/installation These are direct download links for the Microsoft Visual C++ Redistributable packages required to resolve 'ImportError: DLL load failed' on Windows. Choose the appropriate link based on your Python installation's bitness (64-bit or 32-bit). ```url https://aka.ms/vs/16/release/VC_redist.x64.exe ``` ```url https://aka.ms/vs/16/release/VC_redist.x86.exe ``` -------------------------------- ### Install Parselmouth from within Python Source: https://parselmouth.readthedocs.io/en/stable/_sources/installation This Python code demonstrates how to install Parselmouth directly from within a Python interpreter, even if the exact path to the Python executable is unknown. It utilizes the subprocess module to call pip. ```python >>> import sys, subprocess >>> subprocess.call([sys.executable, '-m', 'pip', 'install', 'praat-parselmouth']) ``` -------------------------------- ### Install Parselmouth with Multiple Python Versions Source: https://parselmouth.readthedocs.io/en/stable/_sources/installation This command ensures Parselmouth is installed for the correct Python version when multiple Python installations exist on the system. It uses the Python interpreter's module execution to call pip. ```bash python -m pip install praat-parselmouth ``` -------------------------------- ### Python: Server Process Management Source: https://parselmouth.readthedocs.io/en/stable/examples/web_service This snippet shows how to manage a running server process, specifically how to terminate it. ```Python # Let's shut down the server p.kill() ``` -------------------------------- ### PsychoPy Mock Objects and Setup Source: https://parselmouth.readthedocs.io/en/stable/_sources/examples/psychopy_experiments Sets up mock objects for PsychoPy's TrialHandler and Sound components to allow standalone execution of Parselmouth code. It also initializes variables like filename and seeds the random module for reproducibility. ```Python level = 10 # 'filename' variable is also set by PsychoPy and contains base file name of saved log/output files filename = "data/participant_staircase_23032017" # PsychoPy also create a Trials object, containing e.g. information about the current iteration of the loop # So let's quickly fake this, in this example, such that the code can be executed without errors # In PsychoPy this would be a `psychopy.data.TrialHandler` (https://www.psychopy.org/api/data.html#psychopy.data.TrialHandler) class MockTrials: def addResponse(self, response): print("Registering that this trial was {}successful".format("" if response else "un")) trials = MockTrials() trials.thisTrialN = 5 # We only need the 'thisTrialN' attribute of the 'trials' variable # The Sound component can also be accessed by it's name, so let's quickly mock that as well # In PsychoPy this would be a `psychopy.sound.Sound` (https://www.psychopy.org/api/sound.html#psychopy.sound.Sound) class MockSound: def setSound(self, file_name): print("Setting audio file of Sound component to '{}'".format(file_name)) sound_1 = MockSound() # And the same for our Keyboard component, `key_resp_2`: class MockKeyboard: pass key_resp_2 = MockKeyboard() # Finally, let's also seed the random module to have a consistent output across different runs import random random.seed(42) ``` -------------------------------- ### Plotting Multiple Spectrograms with FacetGrid Source: https://parselmouth.readthedocs.io/en/stable/examples/plotting This example shows how to use Seaborn's FacetGrid to plot multiple custom spectrograms. It reads audio file information from a CSV, processes each audio file to generate a spectrogram and pitch, and plots them in a grid. Dependencies include pandas, seaborn, and parselmouth. ```Python import parselmouth import pandas as pd import seaborn as sns import matplotlib.pyplot as plt def facet_util(data, **kwargs): digit, speaker_id = data[['digit', 'speaker_id']].iloc[0] sound = parselmouth.Sound("audio/{}_{}.wav".format(digit, speaker_id)) plt.figure() plt.plot(sound.xs(), sound.values) plt.xlim([sound.xmin, sound.xmax]) plt.show() spectrogram = sound.to_spectrogram() plt.figure() plt.plot(spectrogram.xs(), spectrogram.ts()) plt.ylim([0, spectrogram.upper_frequency_limit]) plt.show() pitch = sound.to_pitch() plt.figure() plt.plot(pitch.xs(), pitch.values) plt.show() # If not the rightmost column, then clear the right side axis if digit != 5: plt.ylabel("") plt.yticks([]) results = pd.read_csv("other/digit_list.csv") grid = sns.FacetGrid(results, row='speaker_id', col='digit') grid.map_dataframe(facet_util) grid.set_titles(col_template="{col_name}", row_template="{row_name}") grid.set_axis_labels("time [s]", "frequency [Hz]") grid.set(facecolor='white', xlim=(0, None)) plt.show() ``` -------------------------------- ### Update Pip Source: https://parselmouth.readthedocs.io/en/stable/_sources/installation This command updates the pip package installer to its latest version. Keeping pip updated is recommended for a smoother installation process, especially for packages that rely on precompiled wheels. ```bash pip install -U pip ``` -------------------------------- ### FacetGrid for Multiple Spectrograms Source: https://parselmouth.readthedocs.io/en/stable/_sources/examples/plotting This example uses Seaborn's FacetGrid to plot multiple custom spectrograms based on data from a CSV file. The `facet_util` function processes each audio file, generating a spectrogram and pitch contour, and arranging them in a grid based on speaker ID and digit spoken. ```python import pandas as pd def facet_util(data, **kwargs): digit, speaker_id = data[['digit', 'speaker_id']].iloc[0] sound = parselmouth.Sound("audio/{}_{}.wav".format(digit, speaker_id)) draw_spectrogram(sound.to_spectrogram()) plt.twinx() draw_pitch(sound.to_pitch()) # If not the rightmost column, then clear the right side axis if digit != 5: plt.ylabel("") plt.yticks([]) results = pd.read_csv("other/digit_list.csv") grid = sns.FacetGrid(results, row='speaker_id', col='digit') grid.map_dataframe(facet_util) grid.set_titles(col_template="{col_name}", row_template="{row_name}") grid.set_axis_labels("time [s]", "frequency [Hz]") grid.set(facecolor='white', xlim=(0, None)) plt.show() ``` -------------------------------- ### Import Libraries for Plotting Source: https://parselmouth.readthedocs.io/en/stable/_sources/examples/plotting Imports necessary libraries for audio analysis and plotting, including parselmouth, numpy, matplotlib, and seaborn. Sets up plotting styles and figure DPI for better visualization. ```Python import parselmouth import numpy as np import matplotlib.pyplot as plt import seaborn as sns ``` ```Python sns.set() # Use seaborn's default style to make attractive graphs plt.rcParams['figure.dpi'] = 100 # Show nicely large images in this notebook ``` -------------------------------- ### Generate and Draw Spectrogram with Pitch Source: https://parselmouth.readthedocs.io/en/stable/examples/plotting This snippet demonstrates how to pre-emphasize an audio signal, convert it to a spectrogram, and then plot both the spectrogram and the pitch using matplotlib. It requires the Parselmouth and matplotlib libraries. ```Python import parselmouth import matplotlib.pyplot as plt # Assuming 'snd' and 'pitch' are pre-defined Parselmouth objects # snd = parselmouth.Sound(...) # pitch = snd.to_pitch() # If desired, pre-emphasize the sound fragment before calculating the spectrogram pre_emphasized_snd = snd.copy() pre_emphasized_snd.pre_emphasize() spectrogram = pre_emphasized_snd.to_spectrogram(window_length=0.03, maximum_frequency=8000) plt.figure() draw_spectrogram(spectrogram) # Assuming draw_spectrogram is a defined function plt.twinx() draw_pitch(pitch) # Assuming draw_pitch is a defined function plt.xlim([snd.xmin, snd.xmax]) plt.show() ``` -------------------------------- ### Flask Web Server for Pitch Tracking Source: https://parselmouth.readthedocs.io/en/stable/examples/web_service This Python code sets up a Flask web server that accepts audio files via POST requests. It uses Parselmouth to calculate the pitch track of the audio and returns the frequencies as a JSON list. The server saves the uploaded file temporarily for processing. ```Python %%writefile server.py from flask import Flask, request, jsonify import tempfile app = Flask(__name__) @app.route('/pitch_track', methods=['POST']) def pitch_track(): import parselmouth # Save the file that was sent, and read it into a parselmouth.Sound with tempfile.NamedTemporaryFile() as tmp: tmp.write(request.files['audio'].read()) sound = parselmouth.Sound(tmp.name) # Calculate the pitch track with Parselmouth pitch_track = sound.to_pitch().selected_array['frequency'] # Convert the NumPy array into a list, then encode as JSON to send back return jsonify(list(pitch_track)) ``` -------------------------------- ### Find Python Executable Location Source: https://parselmouth.readthedocs.io/en/stable/_sources/installation This Python code snippet helps identify the exact path to the currently running Python executable. This is useful for ensuring that the correct Python installation is targeted when installing packages. ```python >>> import sys >>> print(sys.executable) ``` -------------------------------- ### Parselmouth Sound Channel and Sample Methods Source: https://parselmouth.readthedocs.io/en/stable/genindex Methods to get the number of channels and samples from a Sound object. ```python get_number_of_channels() (parselmouth.Sound method) get_number_of_samples() (parselmouth.Sound method) ``` -------------------------------- ### Running Flask Server in a Subprocess Source: https://parselmouth.readthedocs.io/en/stable/_sources/examples/web_service Starts a Flask development server in a separate subprocess from a Jupyter notebook. It forwards the server's standard output and standard error to the notebook's output, allowing for monitoring. Includes a delay to ensure the server has started. ```Python import os import subprocess import sys import time # Start a subprocess that runs the Flask server p = subprocess.Popen([sys.executable, "-m", "flask", "run"], env=dict(**os.environ, FLASK_APP="server.py"), stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Start two subthreads that forward the output from the Flask server to the output of the Jupyter notebook def forward(i, o): while p.poll() is None: l = i.readline().decode('utf-8') if l: o.write("[SERVER] " + l) import threading threading.Thread(target=forward, args=(p.stdout, sys.stdout)).start() threading.Thread(target=forward, args=(p.stderr, sys.stderr)).start() # Let's give the server a bit of time to make sure it has started time.sleep(2) ``` -------------------------------- ### Calculate and Plot Pitch Source: https://parselmouth.readthedocs.io/en/stable/examples/plotting Calculates the pitch of a sound object using Parselmouth and prepares it for plotting. ```Python pitch = snd.to_pitch() ``` -------------------------------- ### Load and Plot Raw Waveform Source: https://parselmouth.readthedocs.io/en/stable/examples/plotting Loads an audio file into a Parselmouth Sound object and plots its raw waveform using Matplotlib. ```Python snd = parselmouth.Sound("audio/the_north_wind_and_the_sun.wav") plt.figure() plt.plot(snd.xs(), snd.values.T) plt.xlim([snd.xmin, snd.xmax]) plt.xlabel("time [s]") plt.ylabel("amplitude") plt.show() # or plt.savefig("sound.png"), or plt.savefig("sound.pdf") ``` -------------------------------- ### Making HTTP Request to Pitch Track Service Source: https://parselmouth.readthedocs.io/en/stable/examples/web_service This Python code demonstrates how to send an audio file to the running Flask web service using the 'requests' library. It opens a local audio file, sends it as part of a POST request to the '/pitch_track' endpoint, and captures the JSON response containing the pitch frequencies. ```Python import requests import json # Load the file to send files = {'audio': open("audio/the_north_wind_and_the_sun.wav", 'rb')} # Send the HTTP request and get the reply reply = requests.post("http://127.0.0.1:5000/pitch_track", files=files) ``` -------------------------------- ### Pre-emphasize and Spectrogram Calculation Source: https://parselmouth.readthedocs.io/en/stable/_sources/examples/plotting This code demonstrates pre-emphasizing a sound fragment before calculating its spectrogram. It creates a copy of the sound object, applies pre-emphasis, and then computes the spectrogram with specified window length and maximum frequency. ```python # If desired, pre-emphasize the sound fragment before calculating the spectrogram pre_emphasized_snd = snd.copy() pre_emphasized_snd.pre_emphasize() spectrogram = pre_emphasized_snd.to_spectrogram(window_length=0.03, maximum_frequency=8000) ``` -------------------------------- ### Parselmouth Intensity and Spectrum Methods Source: https://parselmouth.readthedocs.io/en/stable/genindex Includes methods for getting average intensity, band density, band energy, and related differences from Intensity and Spectrum objects. ```python get_average() (parselmouth.Intensity method) get_band_density() (parselmouth.Spectrum method) get_band_density_difference() (parselmouth.Spectrum method) get_band_energy() (parselmouth.Spectrum method) get_band_energy_difference() (parselmouth.Spectrum method) ``` -------------------------------- ### Parselmouth API: Sound.to_pitch Source: https://parselmouth.readthedocs.io/en/stable/examples/web_service This APIDOC entry describes the `to_pitch` method of the Parselmouth Sound object. It details how to estimate the pitch track from an audio signal, including accessing the frequency array from the result. This method is crucial for pitch analysis within Parselmouth. ```APIDOC Parselmouth API: Sound.to_pitch() - Estimates the pitch track of a Sound object. - Returns: A Pitch object containing pitch information. - Accessing Frequency: The frequency track can be accessed via `pitch_object.selected_array['frequency']`. ``` -------------------------------- ### Plotting Functions for Spectrogram and Intensity Source: https://parselmouth.readthedocs.io/en/stable/examples/plotting Defines helper functions to plot a spectrogram with a specified dynamic range and an intensity curve. ```Python def draw_spectrogram(spectrogram, dynamic_range=70): X, Y = spectrogram.x_grid(), spectrogram.y_grid() sg_db = 10 * np.log10(spectrogram.values) plt.pcolormesh(X, Y, sg_db, vmin=sg_db.max() - dynamic_range, cmap='afmhot') plt.ylim([spectrogram.ymin, spectrogram.ymax]) plt.xlabel("time [s]") plt.ylabel("frequency [Hz]") def draw_intensity(intensity): plt.plot(intensity.xs(), intensity.values.T, linewidth=3, color='w') plt.plot(intensity.xs(), intensity.values.T, linewidth=1) plt.grid(False) plt.ylim(0) plt.ylabel("intensity [dB]") ``` -------------------------------- ### Draw Spectrogram and Pitch Together Source: https://parselmouth.readthedocs.io/en/stable/_sources/examples/plotting This snippet visualizes both the spectrogram and the pitch contour on the same plot. It sets up a Matplotlib figure, draws the spectrogram, adds a secondary y-axis for the pitch, and sets the x-axis limits. ```python plt.figure() draw_spectrogram(spectrogram) plt.twinx() draw_pitch(pitch) plt.xlim([snd.xmin, snd.xmax]) plt.show() ``` -------------------------------- ### Parselmouth Spectrum Frequency and Bin Methods Source: https://parselmouth.readthedocs.io/en/stable/genindex Provides methods for spectrum analysis, including getting frequency from bin number, highest frequency, and bin width. ```python get_frequency_from_bin_number() (parselmouth.Spectrum method) get_highest_frequency() (parselmouth.Spectrum method) get_bin_width() (parselmouth.Spectrum method) ``` -------------------------------- ### Draw Spectrogram and Intensity Source: https://parselmouth.readthedocs.io/en/stable/_sources/examples/plotting This code snippet visualizes a spectrogram and its corresponding intensity contour. It sets up a Matplotlib figure, draws the spectrogram, adds a secondary y-axis for intensity, and sets the x-axis limits. ```python spectrogram = snd.to_spectrogram() plt.figure() draw_spectrogram(spectrogram) plt.twinx() draw_intensity(intensity) plt.xlim([snd.xmin, snd.xmax]) plt.show() ``` -------------------------------- ### Initialize Parselmouth and Stimuli for PsychoPy Source: https://parselmouth.readthedocs.io/en/stable/_sources/examples/psychopy_experiments Sets up the Python environment for a PsychoPy experiment by importing necessary libraries (parselmouth, numpy, random), defining experimental conditions and stimulus file paths, and scaling audio stimuli to a standard intensity using Parselmouth. This code runs once at the beginning of the experiment. ```Python # ** Begin Experiment ** import parselmouth import numpy as np import random conditions = ['a', 'e'] stimulus_files = {'a': "audio/bat.wav", 'e': "audio/bet.wav"} STANDARD_INTENSITY = 70. stimuli = {} for condition in conditions: stimulus = parselmouth.Sound(stimulus_files[condition]) stimulus.scale_intensity(STANDARD_INTENSITY) stimuli[condition] = stimulus ``` -------------------------------- ### Python: Decode and Plot Pitch Track Source: https://parselmouth.readthedocs.io/en/stable/examples/web_service This snippet shows how to decode a JSON reply containing pitch data and plot it using Matplotlib and Seaborn. It handles zero values by converting them to NaN for proper plotting. ```Python import json import matplotlib.pyplot as plt import seaborn as sns # Assuming 'reply.text' contains the JSON string # reply_text = "[0.0, 0.0, ..., 151.0336292203337]" # Example JSON string # Extract the text from the reply and decode the JSON into a list pitch_track = json.loads(reply_text) print(pitch_track) sns.set() # Use seaborn's default style to make attractive graphs plt.rcParams['figure.dpi'] = 100 # Show nicely large images in this notebook plt.figure() plt.plot([float('nan') if x == 0.0 else x for x in pitch_track], '.') plt.show() ``` -------------------------------- ### Import Libraries for Plotting Source: https://parselmouth.readthedocs.io/en/stable/examples/plotting Imports necessary Python libraries for data manipulation and plotting, including Parselmouth, NumPy, Matplotlib, and Seaborn. ```Python import parselmouth import numpy as np import matplotlib.pyplot as plt import seaborn as sns ``` -------------------------------- ### Parselmouth Initialization for PsychoPy Source: https://parselmouth.readthedocs.io/en/stable/examples/psychopy_experiments Initializes Parselmouth and sets up stimuli for a PsychoPy experiment. Imports necessary libraries, defines experimental conditions and stimulus files, and scales the intensity of audio stimuli. ```Python # ** Begin Experiment ** import parselmouth import numpy as np import random conditions = ['a', 'e'] stimulus_files = {'a': "audio/bat.wav", 'e': "audio/bet.wav"} STANDARD_INTENSITY = 70. stimuli = {} for condition in conditions: stimulus = parselmouth.Sound(stimulus_files[condition]) stimulus.scale_intensity(STANDARD_INTENSITY) stimuli[condition] = stimulus ``` -------------------------------- ### Load and Plot Raw Waveform Source: https://parselmouth.readthedocs.io/en/stable/_sources/examples/plotting Loads an audio file using Parselmouth and plots its raw waveform using Matplotlib. It sets the x-axis limit to the sound's duration and labels the axes. ```Python snd = parselmouth.Sound("audio/the_north_wind_and_the_sun.wav") ``` ```Python plt.figure() plt.plot(snd.xs(), snd.values.T) plt.xlim([snd.xmin, snd.xmax]) plt.xlabel("time [s]") plt.ylabel("amplitude") plt.show() # or plt.savefig("sound.png"), or plt.savefig("sound.pdf") ``` -------------------------------- ### Parselmouth Matrix Methods Source: https://parselmouth.readthedocs.io/en/stable/api_reference Provides documentation for the Parselmouth Matrix class, inheriting from SampledXY. Includes initialization and various methods for accessing and manipulating matrix data, such as converting to a NumPy array, getting values at specific coordinates, applying formulas, and retrieving dimensions and statistics. ```APIDOC _class_ parselmouth.Matrix Bases: `SampledXY` __init__(_* args_, _** kwargs_) as_array(_self :parselmouth.Matrix_) → numpy.ndarray[numpy.float64] at_xy(_self :parselmouth.Matrix_, _x :float_, _y :float_) → float formula(_self :parselmouth.Matrix_, _formula :str_, _from_x :float|None=None_, _to_x :float|None=None_, _from_y :float|None=None_, _to_y :float|None=None_) → None formula(_self :parselmouth.Matrix_, _formula :str_, _x_range :Tuple[float|None,float|None]=(None, None)_, _y_range :Tuple[float|None,float|None]=(None, None)_) → None get_column_distance(_self :parselmouth.Matrix_) → float get_highest_x(_self :parselmouth.Matrix_) → float get_highest_y(_self :parselmouth.Matrix_) → float get_lowest_x(_self :parselmouth.Matrix_) → float get_lowest_y(_self :parselmouth.Matrix_) → float get_maximum(_self :parselmouth.Matrix_) → float get_minimum(_self :parselmouth.Matrix_) → float get_number_of_columns(_self :parselmouth.Matrix_) → int get_number_of_rows(_self :parselmouth.Matrix_) → int get_row_distance(_self :parselmouth.Matrix_) → float get_sum(_self :parselmouth.Matrix_) → float get_value_at_xy(_self :parselmouth.Matrix_, _x :float_, _y :float_) → float get_value_in_cell(_self :parselmouth.Matrix_, _row_number :Positive[int]_, _column_number :Positive[int]_) → float get_x_of_column(_self :parselmouth.Matrix_, _column_number :Positive[int]_) → float ``` -------------------------------- ### Load and Play Audio with Parselmouth Source: https://parselmouth.readthedocs.io/en/stable/examples/pitch_manipulation Demonstrates loading an audio file using Parselmouth and playing it back using IPython.display.Audio. This is the initial step for any audio manipulation task. ```Python import parselmouth sound = parselmouth.Sound("audio/4_b.wav") ``` ```Python from IPython.display import Audio Audio(data=sound.values, rate=sound.sampling_frequency) ``` -------------------------------- ### Find Python Executable Location Source: https://parselmouth.readthedocs.io/en/stable/installation Determines the path to the Python executable within a Python interpreter session. This path can then be used to ensure the correct pip is invoked. ```python >>> import sys >>> print(sys.executable) ``` -------------------------------- ### Pitch Candidate API Source: https://parselmouth.readthedocs.io/en/stable/api_reference API documentation for the Pitch.Candidate class, detailing its initialization method. ```APIDOC Pitch.Candidate: __init__(): Initializes a Pitch.Candidate object. ``` -------------------------------- ### Parselmouth TimeFunction Start and End Time Methods Source: https://parselmouth.readthedocs.io/en/stable/genindex Methods to retrieve the start and end times of a TimeFunction object. ```python get_start_time() (parselmouth.TimeFunction method) get_end_time() (parselmouth.TimeFunction method) ``` -------------------------------- ### Mocking PsychoPy Components Source: https://parselmouth.readthedocs.io/en/stable/examples/psychopy_experiments Mocks essential PsychoPy components like TrialHandler and Sound to simulate their behavior for demonstration purposes. This includes methods for adding responses and setting sound file names. ```python classMockTrials: defaddResponse(self, response): print("Registering that this trial was {}successful".format("" if response else "un")) trials = MockTrials() trials.thisTrialN = 5 # We only need the 'thisTrialN' attribute of the 'trials' variable classMockSound: defsetSound(self, file_name): print("Setting audio file of Sound component to '{}'".format(file_name)) sound_1 = MockSound() classMockKeyboard: pass key_resp_2 = MockKeyboard() importrandom random.seed(42) ``` -------------------------------- ### Parselmouth Sound Sampling Methods Source: https://parselmouth.readthedocs.io/en/stable/genindex Methods to get the sampling frequency and period from Sound objects. ```python get_sampling_frequency() (parselmouth.Sound method) get_sampling_period() (parselmouth.Sound method) ``` -------------------------------- ### Parselmouth FormantUnit Methods Source: https://parselmouth.readthedocs.io/en/stable/api_reference Provides documentation for the __hash__, __index__, __init__, __int__, __ne__, __repr__, and __str__ methods of the FormantUnit class, along with its constants BARK and HERTZ, and properties name and value. ```APIDOC __hash__(_self :object_) → int __index__(_self :parselmouth.FormantUnit_) → int __init__(_self :parselmouth.FormantUnit_, _value :int_) → None __init__(_self :parselmouth.FormantUnit_, _arg0 :str_) → None __int__(_self :parselmouth.FormantUnit_) → int __ne__(_self :object_, _other :object_) → bool __repr__(_self :object_) → str __str__() name(self: handle) -> str BARK _=