Skip to content

Instantly share code, notes, and snippets.

@fauxneticien
Created May 7, 2018 05:44
Show Gist options
  • Save fauxneticien/293f1bbf5b969398e0486311cf279634 to your computer and use it in GitHub Desktop.
Save fauxneticien/293f1bbf5b969398e0486311cf279634 to your computer and use it in GitHub Desktop.
Extract formants from wav file in CSV format using Praat and wrassp::forest trackers
# install.pacakges(...) if you do not have the packages below
library(tidyverse)
library(stringr)
library(wrassp)
library(glue)
wav2formants_csvs <- function(in_file) {
stopifnot(grepl("\\.wav$", in_file))
stopifnot(file.exists(in_file))
absolute_path <- normalizePath(in_file)
praat_formants <- str_replace(absolute_path, "\\.wav$", ".formants.praat.csv")
forest_formants <- str_replace(absolute_path, "\\.wav$", ".formants.forest.csv")
script_file <- tempfile(fileext = ".praat")
# More info, see http://www.fon.hum.uva.nl/praat/manual/Scripting_6_9__Calling_from_the_command_line.html
# Basically, where is the Praat.exe or Praat.app file on your computer?
praat_path <- "/Applications/Praat.app/Contents/MacOS/Praat"
write('
form Test command line calls
sentence input_file
sentence output_file
endform
Read from file: input_file$
To Formant (burg): 0, 5, 5500, 0.025, 50
Down to Table: "no", "yes", 6, "no", 3, "yes", 3, "yes"
Save as comma-separated file: output_file$
', file = script_file)
praat_call <- glue('{praat_path} --run {script_file} "{absolute_path}" "{praat_formants}"')
# Execute praat_call as one would in a command line
system(praat_call)
forest_obj <- forest(listOfFiles = absolute_path, toFile = FALSE)
forest_times <- seq(
from = 0,
to = nrow(forest_obj$fm) / attr(forest_obj, "sampleRate"),
length.out = nrow(forest_obj$fm)
) %>% signif(digits = 4)
forest_df <- cbind(
time = forest_times,
forest_obj$fm %>% tibble::as_data_frame() %>% set_names(paste0("f", 1:ncol(.)))
)
write_csv(x = forest_df, path = forest_formants)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment