praat add to textgrid intervals with mean pitch for every phonem in python using praatio
To add intervals with mean pitch for every phoneme in a TextGrid using the praatio
library in Python, you can follow these steps:
Install PraatIO: If you haven't already, you can install the praatio
library using pip:
pip install praatio
Load the TextGrid: Use praatio
to load your TextGrid file.
Extract Phoneme Intervals: Iterate through the phoneme intervals to calculate the mean pitch for each phoneme.
Create New Intervals: Add new intervals to the TextGrid with the mean pitch values.
Save the Updated TextGrid: Save the modified TextGrid back to a file.
Here's a sample code snippet that demonstrates how to do this:
from praatio import tgio
import numpy as np
import os
def calculate_mean_pitch(pitch_file, start, end):
# Load the pitch file
pitch_data = tgio.openTextGrid(pitch_file)
# Extract pitch values within the specified interval
pitch_values = []
for interval in pitch_data['Pitch'].intervals:
if interval.start >= start and interval.end <= end:
pitch_values.extend(interval.pointList)
# Calculate mean pitch, ignoring NaN values
if pitch_values:
return np.nanmean(pitch_values)
else:
return None
def add_mean_pitch_to_textgrid(textgrid_file, pitch_file, output_file):
# Load the TextGrid
tg = tgio.openTextGrid(textgrid_file)
# Create a new tier for mean pitch
mean_pitch_tier = tgio.IntervalTier("MeanPitch", [])
# Iterate through phoneme intervals
for interval in tg.tiers[0].intervals: # Assuming phonemes are in the first tier
start = interval.start
end = interval.end
mean_pitch = calculate_mean_pitch(pitch_file, start, end)
if mean_pitch is not None:
mean_pitch_tier.addInterval(start, end, str(mean_pitch))
# Add the mean pitch tier to the TextGrid
tg.addTier(mean_pitch_tier)
# Save the updated TextGrid
tg.save(output_file)
# Example usage
textgrid_file = 'path/to/your/textgrid.TextGrid'
pitch_file = 'path/to/your/pitch.TextGrid' # Assuming you have a pitch TextGrid
output_file = 'path/to/your/output.TextGrid'
add_mean_pitch_to_textgrid(textgrid_file, pitch_file, output_file)
.wav
file), you may need to extract pitch values using Praat or another method before using this code.calculate_mean_pitch
function assumes that pitch values are stored in a specific format. You may need to modify it based on how your pitch data is structured.