python - 使用循环连接 .wav 文件

标签 python r bash concatenation wav

我有 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/

相关文章:

r - 综上.lm(P.for.trend) : essentially perfect fit: summary may be unreliable; How to deal with this?

java - 将 kotlin 程序编译为采用 args[0] 并将其打印在控制台中的 java jar 后,如何在 bash 中转义 * 乘法符号?

python - 无法使用opencv打开视频

Python virtualenv -> venv/bin/python 中的新 python 可执行文件

python - 根据二叉树逐级嵌套列表

r - 用最少的步数链接 r 中的记录

python - 如何在Python中访问嵌套函数的变量?

r - 使用 actionButtons 根据索引动态添加和删除 uiOutput 元素

linux - Bash 在传递给另一个 bash shell 时丢弃命令行参数

bash - 使用bash命令从远程服务器读取大文件的前n行