diff --git a/lib/services/audio_handler.dart b/lib/services/audio_handler.dart index 61b32b96..67b8cb89 100644 --- a/lib/services/audio_handler.dart +++ b/lib/services/audio_handler.dart @@ -5,6 +5,7 @@ import 'package:pilipala/models/video_detail_res.dart'; import 'package:get/get.dart'; import 'package:pilipala/plugin/pl_player/index.dart'; import 'package:pilipala/utils/storage.dart'; +import 'package:audio_session/audio_session.dart'; Future initAudioService() async { return await AudioService.init( @@ -26,9 +27,49 @@ class VideoPlayerServiceHandler extends BaseAudioHandler with SeekHandler { static final List _item = []; Box setting = GStrorage.setting; bool enableBackgroundPlay = false; + late AudioSession session; + bool _playInterrupted = false; // 暂时无用 VideoPlayerServiceHandler() { revalidateSetting(); + initSession(); + } + + Future initSession() async { + session = await AudioSession.instance; + session.configure(const AudioSessionConfiguration.speech()); + + session.interruptionEventStream.listen((event) { + if (event.begin) { + switch (event.type) { + case AudioInterruptionType.duck: + // duck or pause + // break; + case AudioInterruptionType.pause: + case AudioInterruptionType.unknown: + pause(); + _playInterrupted = true; + break; + } + } else { + switch (event.type) { + case AudioInterruptionType.duck: + // unduck + // break; + case AudioInterruptionType.pause: + if (_playInterrupted) play(); + break; + case AudioInterruptionType.unknown: + break; + } + _playInterrupted = false; + } + }); + + // 耳机拔出暂停 + session.becomingNoisyEventStream.listen((_) { + pause(); + }); } revalidateSetting() { @@ -64,6 +105,12 @@ class VideoPlayerServiceHandler extends BaseAudioHandler with SeekHandler { final AudioProcessingState processingState; final playing = status == PlayerStatus.playing; + if (playing) { + _playInterrupted = false; + session.setActive(true); + } else { + session.setActive(false); + } if (status == PlayerStatus.completed) { processingState = AudioProcessingState.completed; } else if (isBuffering) { diff --git a/pubspec.lock b/pubspec.lock index 9178dba2..ba2ce7c3 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -82,7 +82,7 @@ packages: source: hosted version: "0.1.1" audio_session: - dependency: transitive + dependency: "direct main" description: name: audio_session sha256: "8a2bc5e30520e18f3fb0e366793d78057fb64cd5287862c76af0c8771f2a52ad" diff --git a/pubspec.yaml b/pubspec.yaml index 17836e7e..bd7f9605 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -90,6 +90,7 @@ dependencies: # 媒体通知 audio_service: ^0.18.12 + audio_session: ^0.1.16 # 音量、亮度、屏幕控制 flutter_volume_controller: ^1.3.0