用循环连接 .wav 文件
Concatenate .wav files with a loop
我有 20 秒的 .wav 文件,我需要将它们组合成 20 分钟长的文件。我按日期修改顺序排列它们,但没有以特定方式命名(这些文件直接来自 AudioMoth 录音,如果需要可以尝试重命名)。
我研究了组合它们的方法,我可以使用 sox 或 ffmpeg,但是我有大约 15000 个文件,因此手动花费的时间有点太长。
希望循环可能吗?这可以通过 bash 或者 python 或 R 实现吗?
下面是我将如何使用 R 和 ffmpeg
来解决这个问题。我确定您可以使用 bash 执行相同类型的循环,但这看起来非常简单:
combiner <- function(path, segments_per_file) {
## Get a list of the wav files
files <- list.files(path = path, pattern = ".wav", full.names = TRUE)
## Split the list of wav files according to the number of files you want to combine at a time
groups <- cumsum(seq_along(files) %% segments_per_file == 1)
file_list <- split(files, groups)
## Loop through the list and use the concat protocol for ffmpeg to combine the files
lapply(seq_along(file_list), function(x) {
a <- tempfile(fileext = ".txt")
writeLines(sprintf("file '%s'", file_list[[x]]), a)
system(sprintf('ffmpeg -f concat -safe 0 -i %s -c copy Group_%s.wav', a, x))
})
}
如果您更喜欢使用 sox
,循环会更简单一些:
combiner <- function(path, segments_per_file) {
files <- list.files(path = path, pattern = ".wav", full.names = TRUE)
groups <- cumsum(seq_along(files) %% segments_per_file == 1)
file_list <- split(files, groups)
lapply(seq_along(file_list), function(x) {
system(sprintf("sox %s Group_%s.wav", paste(file_list[[x]], collapse = " "), x))
})
}
在 R 中,如果您想一次合并 60 个文件,则可以 运行 combiner(path_to_your_wav_files, 60)
。
请注意,合并后的文件将位于您 运行 脚本所在的工作目录中(使用 getwd()
验证它的位置)。
我有 20 秒的 .wav 文件,我需要将它们组合成 20 分钟长的文件。我按日期修改顺序排列它们,但没有以特定方式命名(这些文件直接来自 AudioMoth 录音,如果需要可以尝试重命名)。 我研究了组合它们的方法,我可以使用 sox 或 ffmpeg,但是我有大约 15000 个文件,因此手动花费的时间有点太长。 希望循环可能吗?这可以通过 bash 或者 python 或 R 实现吗?
下面是我将如何使用 R 和 ffmpeg
来解决这个问题。我确定您可以使用 bash 执行相同类型的循环,但这看起来非常简单:
combiner <- function(path, segments_per_file) {
## Get a list of the wav files
files <- list.files(path = path, pattern = ".wav", full.names = TRUE)
## Split the list of wav files according to the number of files you want to combine at a time
groups <- cumsum(seq_along(files) %% segments_per_file == 1)
file_list <- split(files, groups)
## Loop through the list and use the concat protocol for ffmpeg to combine the files
lapply(seq_along(file_list), function(x) {
a <- tempfile(fileext = ".txt")
writeLines(sprintf("file '%s'", file_list[[x]]), a)
system(sprintf('ffmpeg -f concat -safe 0 -i %s -c copy Group_%s.wav', a, x))
})
}
如果您更喜欢使用 sox
,循环会更简单一些:
combiner <- function(path, segments_per_file) {
files <- list.files(path = path, pattern = ".wav", full.names = TRUE)
groups <- cumsum(seq_along(files) %% segments_per_file == 1)
file_list <- split(files, groups)
lapply(seq_along(file_list), function(x) {
system(sprintf("sox %s Group_%s.wav", paste(file_list[[x]], collapse = " "), x))
})
}
在 R 中,如果您想一次合并 60 个文件,则可以 运行 combiner(path_to_your_wav_files, 60)
。
请注意,合并后的文件将位于您 运行 脚本所在的工作目录中(使用 getwd()
验证它的位置)。