How to merge (not concat) two audio files with just_audio for playing both at the same time?
I want to merge it to avoid a hardware limit of just_audio instances playing at the same time. To play with just one instance of just_audio.
How to merge (not concat) two audio files with just_audio for playing both at the same time?
I want to merge it to avoid a hardware limit of just_audio instances playing at the same time. To play with just one instance of just_audio.
The only way I have found to concatenate multiple audio files is to use ffmpeg.
Add this to your pub.dev flutter_ffmpeg and add this class to your lib folder:
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;
  }
}
Example:
final track = await FFmpeg.concatenate(
      [
        "assets/audios/test1.mp3",
        "assets/audios/test2.mp3",
        "assets/audios/test3.mp3",
      ],
      output: "output.mp3"
    );