从一个大型(350 mb).wav制成的S4对象输出许多.wav,切成5秒的片段

时间:2018-09-18 19:00:31

标签: r audio split wav tuner

使用此处找到的R代码:

Split an audio file into pieces of an arbitrary size

我希望将音频切成5秒钟,然后将它们全部导出为.wavs。使用上面的代码后,我可以得到一个具有2564个元素的S4对象,这些元素是每个具有6个插槽的wave。

我希望能够将每个文件另存为.wav,但是有点丢失。到目前为止,这是我的代码。

# 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)])

我对编码和R还是很陌生,所以我很抱歉,答案很简单!

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

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 <- Rec12234@samp.rate

# 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
}