I want to play multiple Audio files in a sequence to form a question for the users.
For that, I tried the AudioPlay
package in the loop but they took some pause to play it in between which did not look good.
So as the alternative I want to combine audio files into a single file to play.
For that I have used ffmpeg_kit_flutter
package, but this returns 1 which means error in merging the files.
List<String> assetAudioFiles = [
'audio/S1B_1.mp3', // Replace with the URLs or local paths of your audio files
'audio/L2_31.mp3',
'audio/S1B_2.mp3',
'audio/L1s20.mp3',
];
Future<List<String>> copyAssetFilesToStorage() async {
List<String> localFilePaths = [];
for (String assetFile in assetAudioFiles) {
String localFilePath = await copyAssetToFile(assetFile);
localFilePaths.add(localFilePath);
}
return localFilePaths;
}
Future<String> copyAssetToFile(String assetFilePath) async {
final ByteData data = await rootBundle.load(assetFilePath);
final Directory tempDir = await getTemporaryDirectory();
final File tempFile =
File('${tempDir.path}/${assetFilePath.split('/').last}');
await tempFile.writeAsBytes(data.buffer.asUint8List(), flush: true);
return tempFile.path;
}
Future<void> combineAudio(List<String> audioFiles) async {
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path;
// Create a temporary output file path
String combinedAudioPath = '$tempPath/output.mp3';
// Prepare the FFmpeg command to concatenate audio files
String inputFiles = audioFiles.join('|');
String command =
'ffmpeg -i "concat:$inputFiles" -acodec copy $combinedAudioPath';
var cmd2 =
"-i ${audioFiles[0]} -i ${audioFiles[1]} -i ${audioFiles[2]} -filter_complex [0:0][1:0][2:0]concat=n=3:v=0:a=1[out] -map [out] $combinedAudioPath";
FFmpegKit.execute(cmd2).then((session) async {
print('session $session');
final returnCode = await session.getReturnCode();
print('returnCode $returnCode');
if (ReturnCode.isSuccess(returnCode)) {
print('Audio files merged successfully $returnCode');
// SUCCESS
} else if (ReturnCode.isCancel(returnCode)) {
print('isCancel $returnCode');
// CANCEL
} else {`enter code here`
print('Error merging audio files: $returnCode');
// audioPlayer.play(DeviceFileSource(outputFilePath));
}
});
}
void combineAndPlayAudio() async {
List<String> localFilePaths = await copyAssetFilesToStorage();
await combineAudio(localFilePaths); //localFilePaths
// Now you can play the combined audio using an audio player or other methods.
}
So can you please let me know how to combine multiple audio files into single or a way to play multiple audio in sequence?
Here the code that I'm using the to concat multiple audios into one file,
-combinedAudioPath is the path of the ouputAudio Please let me know if you need any help