media_key_detector
Triggers events when keyboard media keys are pressed. On MacOS, it registers your app as a Now Playable App, allowing it to respond to media events, regardless of whether the event came from a keyboard, headset, or media remote.
Features
- Captures and triggeres events for the following keys:
- Play / Pause
- Previous / Rewind
- Next / Fast-forward
Rationale
In general media key capture works fine using normal keyboard approaches, such as RawKeyListener or FocusNode. However, it only works on Windows/Linux. In MacOS, the key events are not detected, and often will even send the events to an inactive window, like Music.
Getting started
- Add the latest version of this package:
- Run
flutter pub add media_key_detector
-or- - Edit
pubspec.yaml
and then runflutter pub get
:
dependencies:
media_key_detector: ^latest_version
- Import the package
import 'package:media_key_detector/media_key_detector.dart';
Usage
void _mediaKeyListener(MediaKey mediaKey) {
debugPrint('$mediaKey pressed');
}
@override
void initState() {
super.initState();
mediaKeyDetector.addListener(_mediaKeyListener);
}
@override
void dispose() {
mediaKeyDetector.removeListener(_mediaKeyListener);
super.dispose();
}
/// The following two methods are only really needed if you're relying on
/// the plugin to track the playing state. On MacOS/iOS, this is helpful to
/// display the status in the "Command Center".
/// Get whether the media is playing. Note that it starts out "paused",
/// so if your app plays media on open, you should call
/// [mediaKeyDetector.setIsPlaying(true)]
Future<bool> getIsMediaPlaying() async {
return await mediaKeyDetector.getIsPlaying();
}
/// The app tracks the playing state when the user presses the media key,
/// but there are some cases, i.e. when a play button is pressed on the UI
/// interface, where you may need to set it yourself
Future play() async {
return await mediaKeyDetector.setIsPlaying(isPlaying: true);
}
Code Generation
Developed with 💙 by Very Good Ventures 🦄
A Very Good Flutter Federated Plugin created by the Very Good Ventures Team.
Generated by the Very Good CLI 🤖
Support
Libraries
- media_key_detector
- Plugin which allows you to detect the media buttons on the keyboard, which does not fire for regular key events on MacOS