1

如何将两个音频文件与 just_audio 合并(而不是连接)以同时播放?

我想合并它以避免同时播放 just_audio 实例的硬件限制。只玩一个 just_audio 实例。

4

1 回答 1

1

我发现连接多个音频文件的唯一方法是使用 ffmpeg。将此添加到您的pub.dev flutter_ffmpeg并将此类添加到您的 lib 文件夹中:

class FFmpeg {

  static Future<File> concatenate(List<String> assetPaths, {String output = "new.mp3"})async{

    final directory = await getTemporaryDirectory();
    final file = File("${directory.path}/$output");

    final ffm = FlutterFFmpeg();
    final cmd = ["-y"];
    for(var path in assetPaths){
      final tmp = await copyToTemp(path);
      cmd.add("-i");
      cmd.add(tmp.path);
    }

    cmd.addAll([
      "-filter_complex",
      "[0:a] [1:a] concat=n=${assetPaths.length}:v=0:a=1 [a]",
      "-map", "[a]", "-c:a", "mp3", file.path
    ]);

    await ffm.executeWithArguments(cmd);
    return file;
  }

  static Future<File>copyToTemp(String path)async{
    Directory tempDir = await getTemporaryDirectory();
    final tempFile = File('${tempDir.path}/${path.split("/").last}');
    if(await tempFile.exists()){
      return tempFile;
    }
    final bd = await rootBundle.load(path);
    await tempFile.writeAsBytes(bd.buffer.asUint8List(), flush: true);
    return tempFile;
  }
}

例子:

final track = await FFmpeg.concatenate(
      [
        "assets/audios/test1.mp3",
        "assets/audios/test2.mp3",
        "assets/audios/test3.mp3",
      ],
      output: "output.mp3"
    );
于 2021-03-08T10:47:16.867 回答