Sean Hardison Sean Hardison - 2 months ago 6x
R Question

Fast way for splitting large .wav file using R

For my work I need to analyze large .wav files (>208 MB), and I make use of the R packages seewave and tuneR. I bring each file into the R environment in 30 s chunks, using the readWave function as follows:

tr1_1 = readWave("TR1_edit.WAV", from = 0, to = 0.5, units = "minutes")
tr1_2= readWave("TR1_edit.WAV", from = 0.5, to = 1, units = "minutes")
tr1_3= readWave("TR1_edit.WAV", from = 1, to = 1.5, units = "minutes")
tr1_4= readWave("TR1_edit.WAV", from = 1.5, to = 2, units = "minutes")
tr1_5= readWave("TR1_edit.WAV", from = 2, to = 2.5, units = "minutes")

and so on. This method works, but is not efficient or pretty. Is there a way to import and split up a large .wav class file more efficiently?


If you're loading all of these into memory at the same time, rather than sequential variable names you should be using a list.

tr1 = list()
duration = 0.5
start_times = seq(0, 2, by = duration)

for (i in seq_along(start_times)) {
    tr1[[i]] = readWave('TR1_edit.WAV',
                        from = start_times[i],
                        to = start_times[i] + duration,
                        units = 'minutes')

This is the same principle as why you should use a list of data frames rather than sequentially named data frames.

You could easily wrap this into a function that takes the name of a WAV file as input, gets its length from the metadata, and imports it in 30-second (or a parameterized argument) segments, and returns the list of segments.