play static method
Play audio file
Implementation
static Future<void> play({
required String filePath,
Function()? onComplete,
Function(int currentPosition, int duration)? onProgressUpdate,
Function()? onPlay,
Function()? onPause,
Function()? onResume,
Function(String errorMessage)? onError,
}) async {
if (!Platform.isAndroid && !Platform.isIOS) {
throw UnsupportedError(
'Native AudioPlayer is only supported on Android and iOS');
}
try {
// Setup callbacks
_onComplete = onComplete;
_onProgressUpdate = onProgressUpdate;
_onPlay = onPlay;
_onPause = onPause;
_onResume = onResume;
_onError = onError;
// Setup event channel for callbacks
await _eventSubscription?.cancel();
_eventSubscription = _eventChannel.receiveBroadcastStream().listen(
(dynamic event) {
if (event is Map) {
final eventType = event['type'] as String?;
switch (eventType) {
case 'onComplete':
_onComplete?.call();
break;
case 'onProgressUpdate':
final currentPosition = event['currentPosition'] as int? ?? 0;
final duration = event['duration'] as int? ?? 0;
_onProgressUpdate?.call(currentPosition, duration);
break;
case 'onPlay':
_onPlay?.call();
break;
case 'onPause':
_onPause?.call();
break;
case 'onResume':
_onResume?.call();
break;
case 'onError':
final errorMessage = event['errorMessage'] as String? ?? 'Unknown error';
_onError?.call(errorMessage);
break;
}
}
},
onError: (error) {
print('AudioPlayerPlatform event error: $error');
_onError?.call('Event stream error: $error');
},
);
// Call native method to play
await _methodChannel.invokeMethod('play', {
'filePath': filePath,
});
} catch (e) {
print('AudioPlayerPlatform.play error: $e');
rethrow;
}
}