generateWaveform function
Generates a waveform for the given audio source and returns the waveform data.
audioType
- The type of audio source (asset, URL, or direct file).
audioPath
- The path to the audio file or URL.
Returns a list of waveform amplitude values if successful, otherwise an empty list.
Implementation
Future<List<double>> generateWaveform(
AudioType audioType, String? audioPath) async {
try {
File? audioFile;
// Handle the case where the audio file is stored as an asset.
if (audioType == AudioType.assets && audioPath != null) {
final byteData = await rootBundle.load(audioPath);
final tempDir = await getTemporaryDirectory();
audioFile = File('${tempDir.path}/asset_audio.mp3');
// Save the audio asset data to a temporary file.
await audioFile.writeAsBytes(byteData.buffer.asUint8List());
}
// Handle the case where the audio file is hosted on a URL.
else if (audioType == AudioType.url && audioPath != null) {
final response = await http.get(Uri.parse(audioPath));
final tempDir = await getTemporaryDirectory();
audioFile = File('${tempDir.path}/url_audio.mp3');
// Save the audio data from the URL to a temporary file.
await audioFile.writeAsBytes(response.bodyBytes);
}
// Handle the case where the audio file is already on the device (direct file).
else if (audioType == AudioType.directFile && audioPath != null) {
audioFile = File(audioPath);
}
// If the audio file is successfully created or loaded, extract the waveform.
if (audioFile != null) {
List<double> waves = await extrectWaveform(audioFile);
return waves;
}
// Return an empty list if the audio file could not be processed.
return [];
} catch (e) {
// In case of error, return an empty list.
return [];
}
}