Outputting many .wavs from an S4 object made from a large (350 mb) .wav cut into 5 second segments

49 views Asked by At

Using the R code found here:

Split an audio file into pieces of an arbitrary size

I was looking to slice my audio into 5 second seconds, and then export them all as .wavs. After using the code above I was able to get an S4 object with 2564 elements which are waves with 6 slots each.

I want to be able to save each of these as a .wav, but am a bit lost. Here is my code so far.

# Calling the packages
library(seewave)
library(audio)
library(tuneR)

# Load audio wave into object
Rec12234 <- readWave("012234.wav")

# Make sure the file loaded correctly - should show sample rate, etc.
head(Rec12234)

#Set frequency
freq <- 16000

# Set the length
totlen <- length(Rec12234)

#Set the duration
totsec <- totlen/freq

# How long each sample is (in seconds)
seglen <- 5

#Defining the break points
breaks <- unique(c(seq(0, totsec, seglen), totsec))
index <- 1:(length(breaks)-1)

#Splitting the file
items <- lapply(index, function(i) Rec12234[(breaks[i]*freq):(breaks[i+1]*freq)])

I am very new to coding and R, so I do apologize if the answer is pretty easy!

Thanks for the help!

1

There are 1 answers

1
Edward Carney On BEST ANSWER

You are off to a nice start. Actually, you only need the tuneR package to do what you want. I prefer to use the slots of the Wave object to get my information. That way you can treat files with various sampling rates, etc.

library(tuneR)

# Load audio wave into object
Rec12234 <- readWave("012234.wav")

# Make sure the file loaded correctly - should show sample rate, etc.
head(Rec12234)

#Set frequency
freq <- [email protected]

# Set the length
totlen <- length(Rec12234@left) # 1 channel default is left

#Set the duration
totsec <- totlen/freq

# How long each sample is (in seconds)
seglen <- 5

#Defining the break points
breaks <- unique(c(seq(0, totsec, seglen), totsec))
index <- 1:(length(breaks)-1)

#Splitting the file
items <- lapply(index, function(i) Rec12234@left[(breaks[i]*freq):(breaks[i+1]*freq)])

for (i in 1:length(items)) {
    wavName <- paste('m',i,'.wav',sep='')  # file name
    temp <- Wave(items[i], samp.rate=freq, bit=16) # item into Wave object
    writeWave(temp, wavName) # write the file
}