downloadAudioFromUrl method

  1. @override
Future<String> downloadAudioFromUrl({
  1. required String url,
  2. required String localPath,
  3. ProgressCallback? onDownloadProgress,
})
override

Downloads and processes audio from a network URL

Downloads audio from the specified URL to a local file and optionally processes it (conversion, trimming, waveform extraction).

url - URL of the audio file to download localPath - Local path where the file will be saved onDownloadProgress - Optional callback for download progress (0.0 to 1.0)

Returns the local file path when download completes. Throws NetworkAudioException if download fails.

Implementation

@override
Future<String> downloadAudioFromUrl({
  required String url,
  required String localPath,
  ProgressCallback? onDownloadProgress,
}) async {
  // Validate arguments
  if (url.isEmpty) {
    throw InvalidArgumentsException(
      'URL cannot be empty',
      parameterName: 'url',
      expectedValue: 'non-empty string',
      actualValue: url,
    );
  }

  if (localPath.isEmpty) {
    throw InvalidArgumentsException(
      'Local path cannot be empty',
      parameterName: 'localPath',
      expectedValue: 'non-empty string',
      actualValue: localPath,
    );
  }

  // Set up progress listening
  StreamSubscription<dynamic>? progressSub;
  if (onDownloadProgress != null) {
    progressSub = _progressChannel.receiveBroadcastStream().listen((data) {
      if (data is Map && data['operation'] == 'download') {
        final progress = data['progress'] as double?;
        if (progress != null) {
          onDownloadProgress(progress);
        }
      }
    });
  }

  try {
    final Map<String, dynamic> arguments = {
      'url': url,
      'localPath': localPath,
    };

    final result = await methodChannel
        .invokeMethod<String>('downloadAudioFromUrl', arguments)
        .timeout(const Duration(minutes: 15));

    if (result == null) {
      throw NetworkAudioException(
        'Download failed: No result returned from platform',
        url: url,
        localPath: localPath,
      );
    }

    return result;
  } on PlatformException catch (e) {
    throw _convertPlatformException(e, NetworkAudioException.new, {
      'url': url,
      'localPath': localPath,
    });
  } catch (e) {
    throw NetworkAudioException(
      'Download failed: $e',
      originalError: e,
      url: url,
      localPath: localPath,
    );
  } finally {
    await progressSub?.cancel();
  }
}