我有 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()
验证其位置)。
关于python - 使用循环连接 .wav 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60935498/