ryanheise / audio_service

Flutter plugin to play audio in the background while the screen is off.
786 stars 464 forks source link

API to Stop audio service from running #867

Closed yanivshaked closed 2 years ago

yanivshaked commented 2 years ago

Feature proposal

API to stop the audio service from running, once the user closes the application from background. Using onTaskRemoved to stop the audio is not enough, I would like to completely remove the audio service.

Motivating use case(s)

Application crashes when trying to launch it again after closure from background if audio service is still running.

nt4f04uNd commented 2 years ago

Setting the state to AudioProcessingState.idle is what you want to do to stop the service, this will work in onTaskRemoved. The idea is that when you call stop on just_audio's player, the state of it is broadcasted to service's state, essentially stopping it.

I agree this is currently far from being clear, which is why we have https://github.com/ryanheise/audio_service/issues/655 to document this better.

yanivshaked commented 2 years ago

Looking at the code, calling BaseAudioHandler.stop() sets the state to AudioProcessingState.idle:

    playbackState.add(playbackState.nvalue!
        .copyWith(processingState: AudioProcessingState.idle));

I have tried the following to stop the audio service:

nt4f04uNd commented 2 years ago

This seems another issue, can you file a new issue for that, following the bug template?

yanivshaked commented 2 years ago

Sure, closing this one in favor of a bug report

yanivshaked commented 2 years ago

@nt4f04uNd Unfortunately, I am unable to create a minimal reproduction project for this issue, so I am unable to submit a new bug template. What do you suggest?

nt4f04uNd commented 2 years ago

What plugins are you using in your project?

ryanheise commented 2 years ago

@yanivshaked a good first attempt to build a repro project is to just fork this project and modify the example by adding all of your dependencies to it. Sometimes even the presence of those dependencies will create the right conditions to reproduce the bug.

yanivshaked commented 2 years ago

Many plugins. I've just tried adding all of my plugins to the example project, but it still works.

List of plugins ``` # StreamChannel wrappers for WebSockets. Provides a cross-platform WebSocketChannel API, a cross-platform implementation of that API that communicates over an underlying StreamChannel. web_socket_channel: ^2.1.0 # Annotations for the flutter_sheet_localization_generator package. flutter_localizations: sdk: flutter # Package which will help you to generate pin code fields. Can be useful for OTP for example. pin_code_fields: ^7.3.0 # Simple direct Service Locator that allows to decouple the interface from a concrete implementation and to access the concrete implementation from everywhere in your app. get_it: ^7.2.0 # protobuf: No longer imported since it is now part of the project # Plugin for parsing, formatting and validating international phone numbers. phone_number: ^0.12.0+1 # Plugin provides a cross-platform (iOS, Android) API to request and check permissions. permission_handler: ^8.2.5 # An SVG rendering and widget library for Flutter, which allows painting and displaying Scalable Vector Graphics 1.1 files. flutter_svg: ^0.22.0 # Tuple data structure tuple: ^2.0.0 # An xterm 256 color support library for making pretty logs. ansicolor: ^2.0.1 # Flutter plugin for SQLite, a self-contained, high-reliability, embedded, SQL database engine. sqflite: ^2.0.0+3 # SqfEntity ORM for Flutter/Dart lets you build and execute SQL commands easily and quickly with the help of fluent methods similar to .Net Entity Framework. sqfentity: ^2.1.2+3 # SqfnEntity Model Generator. SQLite ORM for Flutter lets you build and execute SQL commands easily and quickly with the help of fluent methods similar to .Net Entity Framework. sqfentity_gen: ^2.1.2+4 # Toast Library for Flutter, Easily create toast messages in single line of code fluttertoast: git: url: https://github.com/12Tech12/FlutterToast ref: "72558fe" # Flutter plugin providing detailed information about the device (make, model, etc.), and Android or iOS version the app is running on. device_info: ^2.0.2 # A Flutter package that can be used to extract the locales that are currently defined on a device with the current locale set as the first in the list. devicelocale: ^0.5.0 # Carrier Info gets networkType, networkGeneration, mobileCountryCode, mobileCountryCode, e.t.c from both android and ios devices carrier_info: ^2.0.2 # Flutter plugin for getting commonly used locations on the Android & iOS file systems, such as the temp and app data directories. path_provider: ^2.0.2 # Flutter Secure Storage provides API to store data in secure storage. Keychain is used in iOS, KeyStore based solution is used in Android. flutter_secure_storage: ^4.2.0 # Library for 32- and 64-bit signed fixed-width integers. fixnum: 1.0.0 # Flutter Widgets that make it easy to implement the BLoC (Business Logic Component) design pattern. Built to be used with the bloc state management package. flutter_bloc: ^7.1.0 # An abstract class that helps to implement equality without needing to explicitly override == and hashCode. equatable: ^2.0.3 # RxDart is an implementation of the popular reactiveX api for asynchronous programming, leveraging the native Dart Streams api. rxdart: ^0.26.0 # Utility functions and classes related to the 'dart:async' library. async: ^2.8.1 # Contains code to deal with internationalized/localized messages, date and number formatting and parsing, bi-directional text, and other internationalization issues. intl: # A Flutter widget for chat like a speech bubble in Whatsapp and others. bubble: 1.2.1 # RFC4122 (v1, v4, v5) UUID Generator and Parser for all Dart platforms (Web, VM, Flutter) (Guid like generator, used for feeds request Id) uuid: ^3.0.4 # Flutter plugin for querying information about the application package, such as CFBundleVersion on iOS or versionCode on Android. package_info: ^2.0.2 # Firebase Core Flutter SDK firebase_core: ^1.4.0 # Flutter plugin for Firebase Auth, enabling Android and iOS authentication using passwords, phone numbers and identity providers like Google, Facebook and Twitter. firebase_auth: ^3.0.1 # Flutter plugin for Firebase Cloud Storage, a powerful, simple, and cost-effective object storage service for Android and iOS. firebase_storage: ^10.0.1 # Flutter plugin for Firebase Cloud Messaging, a cross-platform messaging solution that lets you reliably deliver messages on Android and iOS. firebase_messaging: ^10.0.4 # Flutter plugin for Firebase Crashlytics. It reports uncaught errors to the Firebase console. firebase_crashlytics: ^2.1.1 # Flutter plugin for Google Analytics for Firebase, an app measurement solution that provides insight on app usage and user engagement on Android and iOS. firebase_analytics: ^8.2.0 # Lets you place headers on scrollable content that will stick to the top of the container whilst the content is scrolled (for chat date headers) sticky_headers: 0.2.0 # A list with helper methods to programmatically scroll to an item. scrollable_positioned_list: ^0.2.0-nullsafety.0 # Dart implementation of sprintf sprintf: ^6.0.0 # Provides server and web apps the ability to load, manipulate, and save images with various image file formats including PNG, JPEG, GIF, BMP, WebP, TIFF, TGA, PSD, PVR, and OpenEXR. image: ^3.0.2 # A flutter plugin for creating a thumbnail from a local video file or from a video URL. video_thumbnail: ^0.4.3 # Flutter plugin for displaying inline video with other Flutter widgets on Android and iOS. video_player: ^2.1.12 # Fetch accurate time or current DateTime object from (NTP) Network Time Protocol server. ntp: ^2.0.0 # scroll to index with fixed/variable row height inside Flutter scrollable widget scroll_to_index: ^2.1.0 # A cross platform plugin for displaying and scheduling local notifications for Flutter applications with the ability to customise for each platform. flutter_local_notifications: ^6.0.0 # Flutter plugin for launching a URL on Android and iOS. Supports web, phone, SMS, and email schemes. url_launcher: ^6.0.9 # A composable, multi-platform, Future-based API for HTTP requests. http: ^0.13.3 # Automatically generate code for converting to and from JSON by annotating Dart classes. json_serializable: ^6.0.0 # Classes and helper functions that support JSON code generation via the `json_serializable` package. json_annotation: ^4.3.0 # Flutter plugin for discovering the state of the network (WiFi & mobile/cellular) connectivity on Android and iOS. connectivity: ^3.0.6 # A flutter package for drawing dashed circles. Can also be used with CustomPaint. dashed_circle: ^0.0.2 # A Flutter implementation of slidable list item with directional slide actions that can be dismissed. flutter_slidable: git: url: https://github.com/12Tech12/flutter_slidable ref: 6ef1e49 # A Flutter widget rendering static HTML and CSS as Flutter widgets. flutter_html: ^2.1.0 # A widget that can be dragged and scrolled in a single gesture and snapped to a list of extents. sliding_sheet: ^0.5.0 # Photo View provides a gesture sensitive zoomable widget. Photo View is largely used to show interacive images and other stuff such as SVG. photo_view: ^0.13.0 # A flexible widget for user notification. Customize your text, button, duration, animations and much more. For Android devs, it is made to replace Snackbars and Toasts. another_flushbar: ^1.10.24 # A Flutter plugin for Android and iOS for sharing text, image, video and file with system ui. share_extend: ^2.0.0 # Flutter plugin for sharing content via the platform share UI, using the ACTION_SEND intent on Android and UIActivityViewController on iOS. share_plus: ^3.0.4 # A plugin for handling Vibration API on iOS and Android devices vibration: ^1.7.4-nullsafety.0 # Mutual exclusion with implementation of normal and read-write mutex mutex: ^3.0.0 # Support for iOS NSUserDefaults shared between App Groups shared_preferences_app_group_ios: git: url: https://github.com/yanivshaked/shared_preferences_app_group_ios.git ref: "e9f10c8" version: 0.0.5 #path: C:\dev\12Tech12\git\shared_preferences_app_group_ios #path: ../../shared_preferences_app_group_ios # charset_converter: ^1.0.3 Charset/encoding converter that uses underlying platform - no external dependencies charset_converter: ^2.0.0 # Flutter library to load and cache network images. Can also be used with placeholder and error widgets. cached_network_image: ^3.0.0 # A Flutter plugin for getting information about and controlling the camera on Android and iOS. Supports previewing the camera feed, capturing images, capturing video, and streaming image buffers to dart. # !!! *** NOTE *** version 0.8.1+6 having a bug caused by listening to controller inside CameraPreview. ** make sure it is fixed before upgrading!!!! camera: 0.9.4+2 # native_device_orientation: ^0.4.3: A Flutter plugin for reading device's native orientation, either from UI orientation or from sensors native_device_orientation: ^1.0.0 # An audio/video/image picker in pure Dart which is the same with WeChat, support multi picking. wechat_assets_picker: ^6.2.1 # A Flutter widget that can be expanded or collapsed by clicking on a header or an icon. expandable: ^5.0.1 # Reorderable table, row, column, wrap, sliver list that allow drag and drop of their children. reorderables: ^0.4.1 # Retrieve App Group directory on iOS. Port of FileManager.containerURL to Flutter. app_group_directory: ^2.0.0 # A simple and versatile autocomplete text field for flutter, supporting multiple datatypes. autocomplete_textfield_ns: ^2.0.0 # Flutter plugin to render PDF pages as images on Web, MacOS, Android and iOS. flutter_cached_pdfview: ^0.4.0-nullsafety # A plugin that provides you with intermediate PDF rendering APIs and easy-to-use Flutter Widgets. pdf_render: ^1.0.11 # Compress image with native code(objc kotlin), it's faster. This library can work on android/ios. flutter_image_compress: ^1.0.0 # Light library of video manipulation of Flutter. Compress video, remove audio, get video thumbnail from dart code. video_compress: ^3.1.0 # Library that allows you to display progress widgets based on percentage, can be Circular or Linear, you can also customize it to your needs. percent_indicator: ^3.3.0-nullsafety.1 # Support for launching URL links on external browser (iOS only) url_launcher_ios: git: url: https://github.com/yanivshaked/url_launcher_ios ref: "2c94bd6" version: 0.0.3 # A widget that detects the visibility of its child and notifies a callback. visibility_detector: ^0.2.0 # A plugin to manage a device's sound mode for android. This plugin also supports requesting the required permissions to modify the device's sound mode for Android API 24 and above. sound_mode: ^2.0.1 # A complete api for audio playback and recording. Audio player, audio recorder, media player, media recorder, sound player, sound recorder. tau_sound: git: url: https://github.com/12Tech12/tau.git ref: 43056eb path: tau_sound # A feature-rich audio player for Flutter. Loop, clip and concatenate any sound from any source (asset/file/URL/stream) in a variety of audio formats with gapless playback. just_audio: git: url: https://github.com/12Tech12/just_audio.git ref: "13d55fb" path: "just_audio" # A plugin to support audio filters for flutter audio_filters: git: url: https://github.com/12Tech12/audio_filters.git ref: "db50ca9" # path: C:\dev\12Tech12\git\audio_filters # Flutter plugin to play audio in the background while the screen is off. audio_service: ^0.18.1 # Share an email to device Email - Client supports multiple Attachments flutter_mailer: ^2.0.0 # A small library for un-escaping HTML. Supports all Named Character References, Decimal Character References and Hexadecimal Character References. html_unescape: ^2.0.0 # A package that allows you to use a native file explorer to pick single or multiple absolute file paths, with extension filtering support file_picker: ^3.0.0 # A plug-in that can call native APP to open files with string result in flutter open_file: ^3.2.1 # A material design slider and range slider, horizontal and vertical, with RTL support and lots of options and customizations for flutter flutter_xlider: git: url: https://github.com/Ksomething/flutter_xlider.git feature: null-safety-support # Flutter plugin for accepting incoming links - App/Deep Links (Android), Universal Links and Custom URL schemes (iOS). uni_links2: ^0.6.0+2 # A date time picker for flutter, you can choose date / time / date&time in English Dutch and Chinese, and you can also custom your own picker content # waiting for compilation warning version fix flutter_datetime_picker: git: url: https://github.com/Realank/flutter_datetime_picker.git ref: "eb97011" # A flutter plugin that enables flutter apps to receive sharing photos, text or url from other apps receive_sharing_intent: ^1.4.5 # A Dart library implementing cryptographic algorithms and primitives, modeled on the BouncyCastle library. pointycastle: ^3.2.0 # Flutter plugin for Facebook App Events, an app measurement solution that provides insight on app usage and user engagement in Facebook Analytics. facebook_app_events: ^0.14.2 # cropping images image_cropper: ^1.4.1 # A HSV(HSB)/HSL color picker inspired by chrome devtools and a material color picker for your flutter app. flutter_colorpicker: ^0.6.0 # Flutter Screenshot Package (Runtime). Capture any Widget as an image. screenshot: ^1.2.3 # A highly customizable typeahead (autocomplete) text input field for Flutter flutter_typeahead: ^3.2.0 # A Flutter plugin for the Android Play Install Referrer API. You can use it to securely retrieve referral content from Google Play. android_play_install_referrer: ^0.1.1 # A draggable Flutter widget that makes implementing a SlidingUpPanel much easier sliding_up_panel: ^2.0.0+1 # A Flutter plugin for opening iOS and Android phone settings from an app. app_settings: ^4.1.1 # A wrapper around InheritedWidget to make them easier to use and more reusable. provider: ^6.0.1 # Plugin that allows you to keep the device screen awake, i.e. prevent the screen from sleeping on Android, iOS, and web. wakelock: ^0.5.6 # A free and unlimited Google Translate API for Dart. You can use it for translate strings and text for educational purpose. translator: ^0.1.7 # A Flutter plugin to check the availability of Google Play Services on an Android device. google_api_availability: ^3.0.1 # A widget that rebuilds itself on scheduled, periodic, or dynamically generated time events. timer_builder: ^2.0.0 # A plugin that listens to children inside scrollview widgets_visibility_provider: ^3.0.1 # Collections and utilities functions and classes related to collections. collection: ^1.15.0-nullsafety.4 # A Flutter plugin to easily handle realtime location in iOS and Android. Provides settings for optimizing performance or battery. location: ^4.3.0 # Add beautiful and trending tab indicators directly to your default Flutter TabBar tab_indicator_styler: ^2.0.0-null-safety # Plugin to update the app badge on the launcher (both for Android and iOS) flutter_app_badger: ^1.3.0 # Create awesome and powerful modal bottom sheets. Material, Cupertino iOS 13 or create your own style modal_bottom_sheet: ^2.0.0 # With this library you can convert HEIC/HEIF file to JPEG image easily heic_to_jpg: ^0.2.0 # Flutter plugin for reading and writing simple key-value pairs. Wraps NSUserDefaults on iOS and SharedPreferences on Android. shared_preferences: ^2.0.6 # A vertical fullscreen scroll implementation that snaps in place, similar to the T**T** app tiktoklikescroller: ^0.1.6 # Like Button is a flutter library that allows you to create a button with animation effects similar to Twitter's heart when you like something. like_button: ^2.0.2 # A bit array (also known as BitMap, BitSet, BitString, or BitVector) is an array data structure that compactly stores bits. bit_array: ^2.2.0 # Generic cache manager for flutter. Saves web files on the storages of the device and saves the cache info using sqflite. flutter_cache_manager: ^3.1.2 # Flutter Widget that make it easy to implement custom refresh indicator. custom_refresh_indicator: ^1.0.0 # A Flutter widget that scrolls text infinitely. Provides many customizations including custom scroll directions, durations, curves as well as pauses after every round. marquee: ^2.2.0 # Flutter widget that automatically resizes text to fit perfectly within its bounds. auto_size_text: ^3.0.0-nullsafety.0 # RotatedCornerDecoration package was developed to create and apply corner triangle badges. It provides auto rotation of TextSpans. rotated_corner_decoration: ^2.0.0 # Flutter plugin to obtain available keyboard languages (iOS and Android). keyboard_languages: ^0.1.4 # A Flutter plugin for AppsFlyer SDK. Supports iOS and Android. appsflyer_sdk: ^6.4.0+1 # A flutter widget which progressively loads large images using Low Quality Image Placeholders. progressive_image: ^2.0.0 # Sets the iOS audio session category and Android audio attributes for your app, and manages your app's audio focus, mixing and ducking behaviour. audio_session: ^0.1.5 # Allows to kindly ask users to rate your app if custom conditions are met (eg. install time, number of launches, etc...). rate_my_app: ^1.1.1 # A handful collection of some cool progress indicators and text animators. progress_indicators: ^1.0.0 # A flutter package project which contains a collection of cool and beautiful text animations. animated_text_kit: ^4.2.1 # Flutter port of the official YouTube iFrame player API. Supports web & mobile platforms. youtube_player_iframe: ^2.2.2 ```
ryanheise commented 2 years ago

Unfortunately in that case, you might want to try debugging the open_file plugin yourself (which is the plugin that is actually crashing, according to your error):

at com.crazecoder.openfile.OpenFilePlugin.onAttachedToActivity(OpenFilePlugin.java:400)

So what exactly is on line 400 of OpenFilePlugin.java?

yanivshaked commented 2 years ago

Bravo!! I missed that. Seems like this issue is referenced and solved here: https://github.com/crazecoder/open_file/issues/162

Testing now.

yanivshaked commented 2 years ago

It works 👍 Still, the application misbehaves; Once I'm closing it from the background, I would expect it to "cleanly" start when launching it again. Instead, it returns to the last page I was viewing on the application before closing it. That gives extra weight to my original feature request, how to completely stop the audio service from running in background?

ryanheise commented 2 years ago

I think @nt4f04uNd 's first response is appropriate here, and i would suggest thumbing up that other issue to improve the documentation.

yanivshaked commented 2 years ago

I have followed @nt4f04uNd response and set the state to AudioProcessingState.idle but problem remains. Just to make sure we are on the same page here, following is the scenario:

Is this behavior the expected behavior? I would expect the application to start from scratch.

ryanheise commented 2 years ago

Hi @yanivshaked there are more variables in play that influence the behaviour than what you have described above so this sort of thing is difficult to answer without a repro case. But I would say in general that what is defined as "expected" is what the documentation says. I wouldn't want to get into what's expected without having this explicit in the documentation, and hence:

  1. If the documentation is not clear, let's create or follow a documentation request to make that explicit.
  2. If the documentation is clear but it doesn't support the behaviour you expect, let's submit a feature request.

Then I can get to work either implementing the new behaviour or correcting existing behaviour.

yanivshaked commented 2 years ago

The documentation is clear to me now (setting state to AudioProcessingState.idle to remove player from notification), and it doesn't support the behavior I expect. I can easily create a reproduction project for the above scenario. I am not sure about semantics, since the original feature request (this issue) is to the best of my understanding what must be done to support the expected behavior.

ryanheise commented 2 years ago

I think a new issue is better because technically,

  1. There is already an API to stop the service, and
  2. Your motivating use case as stated is no longer applicable (i.e. it doesn't crash)

Feature proposal

API to stop the audio service from running, once the user closes the application from background. Using onTaskRemoved to stop the audio is not enough, I would like to completely remove the audio service.

Motivating use case(s)

Application crashes when trying to launch it again after closure from background if audio service is still running.

In a new issue, you may be able to better describe the motivating scenario of not retaining the main activity's state after re-entering the main activity after the task was removed.

yanivshaked commented 2 years ago

Ack

github-actions[bot] commented 2 years ago

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs, or use StackOverflow if you need help with audio_service.