Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/hirbod/react-native-volume-manager
React Native module which adds the ability to change the system volume on iOS and Android, listen to volume changes and supress the native volume UI to build your own volume slider or UX. It can listen to iOS mute switch and ringer mode changes on Android (and let you set the ringer mode)
https://github.com/hirbod/react-native-volume-manager
android expo ios react react-native
Last synced: 4 days ago
JSON representation
React Native module which adds the ability to change the system volume on iOS and Android, listen to volume changes and supress the native volume UI to build your own volume slider or UX. It can listen to iOS mute switch and ringer mode changes on Android (and let you set the ringer mode)
- Host: GitHub
- URL: https://github.com/hirbod/react-native-volume-manager
- Owner: hirbod
- License: mit
- Created: 2022-06-02T14:00:53.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2024-03-28T14:55:19.000Z (10 months ago)
- Last Synced: 2024-05-02T05:04:26.616Z (8 months ago)
- Topics: android, expo, ios, react, react-native
- Language: TypeScript
- Homepage:
- Size: 4.14 MB
- Stars: 215
- Watchers: 3
- Forks: 13
- Open Issues: 10
-
Metadata Files:
- Readme: README.md
- Contributing: CONTRIBUTING.md
- Funding: .github/FUNDING.yml
- License: LICENSE
Awesome Lists containing this project
README
![React Native Volume Manager Ringer Mute Silent Switch](gh-banner.png)
# react-native-volume-manager
Take control of system volume on **iOS** and **Android** with this powerful native package. Seamlessly adjust volume levels, track changes, and design custom sliders for a tailored user experience. With an intuitive API, you can access the current volume, detect the silent switch on iOS, and monitor ringer mode changes on Android.
| ![React Native Volume Manager](ios-preview.gif) | ![React Native Volume Manager](android-preview.gif) |
| ----------------------------------------------- | --------------------------------------------------- |## Features
- Adjust system volume
- Monitor volume changes
- Suppress default volume UI
- Access current volume level
- Detect silent switch status (iOS)
- Enable/disable audio session and change category (iOS)
- Track ringer mode changes (Android)## Installation
Using npm:
```sh
npm install react-native-volume-manager
```Using Yarn:
```sh
yarn add react-native-volume-manager
```New and old architecture are supported. React Native 0.76+ is required. iOS 15+ is required.
If you are using Expo, make sure to use expo-build-properties to set the minimum iOS version to 15. (Default in SDK 52+). Kotlin 1.8+ is required. No support for older versions!```json
[
"expo-build-properties",
{
"android": {
"compileSdkVersion": 34,
"targetSdkVersion": 34,
"buildToolsVersion": "34.0.0"
},
"ios": {
"deploymentTarget": "15.2"
}
}
]
```> Note: This library is incompatible with Expo Go. To use it, you can install a [custom development client](https://docs.expo.dev/develop/development-builds/create-a-build/).
## Simulators / Emulators
- iOS: The AVAudioSession API provides control over audio behaviors and settings on iOS devices. However, hardware-specific features like volume control and audio route selection are unavailable on macOS, where the simulator runs. Consequently, this package only works on a physical device, as events won’t trigger in the simulator.
- Android: It runs on both a real device (API level 21+) and the emulator (API level 33+).
## Web
This library is not functional on the web. While the package exports no-op methods for web usage, allowing you to include it without any issues, these methods have no actual effect.
## Usage
All methods are available under the `VolumeManager` namespace or can be imported directly. Here are some examples:
```tsx
import { VolumeManager } from 'react-native-volume-manager';// Disable the native volume toast globally (iOS, Android)
VolumeManager.showNativeVolumeUI({ enabled: true });// Set the volume (value between 0 and 1)
await VolumeManager.setVolume(0.5);// Get the current volume async
const { volume } = await VolumeManager.getVolume();// Listen to volume changes
const volumeListener = VolumeManager.addVolumeListener((result) => {
console.log(result.volume);// On Android, additional volume types are available:
// music, system, ring, alarm, notification
});// Remove the volume listener
volumeListener.remove();
```## iOS Audio Session Management
This section provides methods related to AVAudioSession on iOS. For example:
```tsx
import { VolumeManager } from 'react-native-volume-manager';// Enable or disable iOS AudioSession
VolumeManager.enable(true, true); // Enable async
VolumeManager.enable(false, true); // Disable async, non-blocking// Activate or deactivate the audio session
VolumeManager.setActive(true, true); // Activate async
VolumeManager.setActive(false, true); // Deactivate async, non-blocking
```## iOS Mute Switch Listener
To monitor the mute switch status on iOS, you can use the following:
```tsx
import { VolumeManager } from 'react-native-volume-manager';const silentListener = VolumeManager.addSilentListener((status) => {
console.log(status.isMuted);
console.log(status.initialQuery);
});// Remove the silent listener
silentListener.remove();
```## Android Ringer Listener
To listen to ringer mode changes on Android, you can use the following:
```tsx
import { VolumeManager } from 'react-native-volume-manager';const ringerListener = VolumeManager.addRingerListener((status) => {
console.log(status.ringerMode);
});// Remove the ringer listener
VolumeManager.removeRingerListener(ringerListener);
```## useSilentSwitch hook
`useSilentSwitch` is a custom React hook that monitors the silent switch on an iOS device. The nativeIntervalCheck parameter (optional) allows you to set the interval at which the silent switch status is checked in seconds. If the parameter is not provided, a default interval is used (2.0).
The hook returns an object with two properties: isMuted (which represents the ring/mute switch position) and initialQuery (which indicates whether the reported status is the first one after the application launch). On non-iOS platforms or for the first call, the hook returns undefined. This hook is only applicable to iOS.
```tsx
import React from 'react';
import { View, Text } from 'react-native';
import { useSilentSwitch } from 'react-native-volume-manager';export default function App() {
const status = useSilentSwitch();return (
Silent Switch Status:
{status ? (
Is Muted: {status.isMuted ? 'YES' : 'NO'}
Is Initial Query: {status.initialQuery ? 'YES' : 'NO'}
) : (
Fetching...
)}
);
}
```In this example, `useSilentSwitch` is used to monitor the status of the silent switch on iOS devices. The status of the switch (`isMuted`) and whether it's the initial query (`initialQuery`) are displayed. If the status is not available yet, "Fetching..." is displayed.
### useRingerMode Hook
You can use the `useRingerMode` hook to get and set the ringer mode on Android:
```tsx
import React from 'react';
import { View, Text, Button } from 'react-native';
import {
useRingerMode,
RINGER_MODE,
RingerModeType,
} from 'react-native-volume-manager';const modeText = {
[RINGER_MODE.silent]: 'Silent',
[RINGER_MODE.normal]: 'Normal',
[RINGER_MODE.vibrate]: 'Vibrate',
};export default function App() {
const { mode, error, setMode } = useRingerMode();return (
Ringer Mode: {mode !== undefined ? modeText[mode] : null}
setMode(RINGER_MODE.silent)} />
setMode(RINGER_MODE.normal)} />
setMode(RINGER_MODE.vibrate)} />
{error?.message}
);
}
```## API
The `VolumeManager` API provides an interface for controlling and observing volume settings on iOS and Android devices. The API is designed to offer a consistent experience across both platforms where possible, with some platform-specific functionality provided where necessary.
### Cross-platform methods:
- `showNativeVolumeUI(config: { enabled: boolean }): Promise`: This asynchronous function allows you to control the visibility of the native volume UI when volume changes occur.
- `getVolume(): Promise`: Asynchronously fetches the current volume level and returns a promise that resolves to an object, `VolumeResult`, containing the current volume information.
- `setVolume(value: number, config?: VolumeManagerSetVolumeConfig): Promise`: Allows you to programmatically adjust the device's volume level. The `value` parameter should be between 0 and 1, and `config` parameter is an optional object for additional configuration settings.
- `addVolumeListener(callback: (result: VolumeResult) => void): EmitterSubscription`: Allows you to add a listener that will be called when the device's volume changes. The listener receives an object, `VolumeResult`, that contains the updated volume information.
### iOS-only methods:
- `enable(enabled: boolean, async: boolean): Promise`: Enables or disables the audio session. Enabling the audio session sets the session's category to 'ambient', allowing it to mix with other audio.
- `setActive(value: boolean, async: boolean): Promise`: Activates or deactivates the audio session. Deactivating the session reactivates any sessions that were interrupted by this one.
- `setCategory(value: AVAudioSessionCategory, mixWithOthers?: boolean): Promise`: Sets the category for the AVAudioSession in your iOS app. `mixWithOthers` is an optional parameter that, if true, allows your audio to mix with audio from other apps.
- `setMode(mode: AVAudioSessionMode): Promise`: Sets the mode for the AVAudioSession in your iOS app.
- `enableInSilenceMode(value: boolean): Promise`: If value is true, this function allows your app to play audio even when the device is in silent mode. When value is false, audio will not play in silent mode.
- `setNativeSilenceCheckInterval(value: number)`: Sets the interval at which the native system checks the state of the silent switch.
- `addSilentListener(callback: RingMuteSwitchEventCallback): EmitterSubscription | EmitterSubscriptionNoop`: Adds a listener that will be called when the silent switch state changes.
### Android-only methods:
- `getRingerMode(): Promise`: Asynchronously fetches the current ringer mode of the device (silent, vibrate, or normal).
- `setRingerMode(mode: RingerModeType): Promise`: Sets the device's ringer mode.
- `isAndroidDeviceSilent(): Promise`: Asynchronously checks if the device is in a silent state (including silent mode, vibrate mode, or muted volume / do not disturb mode).
- `addRingerListener(callback: RingerEventCallback): EmitterSubscription | EmitterSubscriptionNoop`: Adds a listener that will be called when the ringer mode changes.
- `removeRingerListener(listener: EmitterSubscription | EmitterSubscriptionNoop): void`: Removes a previously added ringer mode listener.
- `checkDndAccess(): Promise`: Asynchronously checks if 'Do Not Disturb' access has been granted.
- `requestDndAccess(): Promise`: Initiates a request for 'Do Not Disturb' access.
Please note that while this API tries to provide a consistent experience across both platforms, some methods are platform-specific due to the differences in how iOS and Android handle
## Contributing
See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow.
## Special thanks
- Uses code from https://github.com/c19354837/react-native-system-setting
- Uses code from https://github.com/zmxv/react-native-sound
- Uses code from https://github.com/vitorverasm/react-native-silent
- Uses code from https://github.com/GeorgyMishin/react-native-silent-listener
- Fully implements https://github.com/reyhankaplan/react-native-ringer-modeI used parts, or even the full source code, of these libraries (with plenty of adjustments and rewrites to TypeScript) to make this library work on Android and iOS and to have a mostly unified API that handles everything related to volume. Since many of the packages I found were unmaintained or abandoned and only solved some of the issues, I decided to create my own. I hope you don't mind it and find it useful!
## License
MIT