react-native-voice-frequency
v0.1.0
Published
Real-time audio level monitoring for React Native
Readme
react-native-voice-frequency
Real-time audio level monitoring and voice detection for React Native with native performance. Perfect for voice recording interfaces, audio visualizers, and voice-activated features.
✨ Features
- 🎙️ Real-time audio level monitoring - Get live audio input levels as the user speaks
- 🎯 Voice activity detection - Automatically detect when voice is present
- 📊 Multiple metrics - Level (0-1), decibels (dB), and elapsed time
- ⚡ Native performance - Written in Kotlin (Android) and Swift (iOS)
- ♿ Accessibility built-in - Screen reader announcements for state changes
- 🎨 Easy to use - Simple React hook API
- 📱 Cross-platform - Works on iOS and Android
📸 Demo
[Listening...] 🎤 00:15
━━━━━━━━━━━━━━━━━━━━ Voice detected🚀 Installation
npm install react-native-voice-frequency
# or
yarn add react-native-voice-frequencyiOS
cd ios && pod install && cd ..Android
No additional steps required. The package will be auto-linked.
Permissions
iOS
Add to your Info.plist:
<key>NSMicrophoneUsageDescription</key>
<string>We need access to your microphone to record audio</string>Android
Add to your AndroidManifest.xml:
<uses-permission android:name="android.permission.RECORD_AUDIO" />Request the permission at runtime:
import { PermissionsAndroid, Platform } from 'react-native';
async function requestMicrophonePermission() {
if (Platform.OS === 'android') {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
{
title: 'Microphone Permission',
message: 'This app needs access to your microphone',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
}
);
return granted === PermissionsAndroid.RESULTS.GRANTED;
}
return true;
}📖 Usage
Basic Example
import React from 'react';
import { View, Text, Button } from 'react-native';
import { useVoiceFrequency } from 'react-native-voice-frequency';
export default function App() {
const {
isListening,
audioLevel,
error,
start,
stop,
formattedTime
} = useVoiceFrequency();
return (
<View>
<Text>Audio Level: {Math.round(audioLevel.level * 100)}%</Text>
<Text>Time: {formattedTime}</Text>
<Text>
{audioLevel.isVoiceDetected ? 'Voice detected ✓' : 'Listening...'}
</Text>
{error && <Text style={{ color: 'red' }}>{error}</Text>}
<Button
title={isListening ? 'Stop' : 'Start'}
onPress={isListening ? stop : start}
/>
</View>
);
}Advanced Example with Visualizer
import React, { useRef, useEffect } from 'react';
import { View, Animated, StyleSheet } from 'react-native';
import { useVoiceFrequency } from 'react-native-voice-frequency';
export default function AudioVisualizer() {
const { audioLevel, start, stop } = useVoiceFrequency();
const barAnimations = useRef(
[...Array(20)].map(() => new Animated.Value(0.2))
).current;
useEffect(() => {
start();
return () => stop();
}, []);
useEffect(() => {
barAnimations.forEach((anim, index) => {
const targetHeight = 0.2 + (audioLevel.level * 0.8) +
(Math.sin(index * 0.5) * 0.2);
Animated.timing(anim, {
toValue: targetHeight,
duration: 100,
useNativeDriver: false,
}).start();
});
}, [audioLevel.level]);
return (
<View style={styles.container}>
{barAnimations.map((anim, index) => (
<Animated.View
key={index}
style={[
styles.bar,
{
height: anim.interpolate({
inputRange: [0, 1],
outputRange: ['10%', '100%'],
}),
backgroundColor: audioLevel.isVoiceDetected
? '#3B82F6'
: '#EF4444',
},
]}
/>
))}
</View>
);
}
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
height: 60,
gap: 3,
},
bar: {
flex: 1,
borderRadius: 2,
minHeight: 10,
},
});🎯 API Reference
useVoiceFrequency()
A React hook that provides access to voice frequency monitoring.
Returns
{
isListening: boolean; // Whether monitoring is active
audioLevel: AudioLevel; // Current audio metrics
error: string | null; // Error message if any
start: () => Promise<void>; // Start monitoring
stop: () => Promise<void>; // Stop monitoring
formattedTime: string; // Formatted elapsed time (MM:SS)
}AudioLevel Type
interface AudioLevel {
level: number; // Normalized audio level (0-1)
db: number; // Audio level in decibels
elapsedMs: number; // Milliseconds since start
isVoiceDetected: boolean; // Whether voice is detected
frameCount: number; // Number of audio frames processed
state: 'listening' | 'idle'; // Current state
}VoiceFrequency (Direct API)
Low-level API if you prefer not to use the hook:
import { VoiceFrequency } from 'react-native-voice-frequency';
// Start monitoring
await VoiceFrequency.start();
// Stop monitoring
await VoiceFrequency.stop();
// Test multiplication (utility)
const result = await VoiceFrequency.multiply(5, 10); // Returns 50Events
Listen to audio level events directly:
import { NativeModules, NativeEventEmitter } from 'react-native';
const { VoiceFrequency } = NativeModules;
const eventEmitter = new NativeEventEmitter(VoiceFrequency);
const subscription = eventEmitter.addListener('VF_AUDIO_LEVEL', (event) => {
console.log('Audio Level:', event.level);
console.log('Voice Detected:', event.isVoiceDetected);
});
// Don't forget to cleanup
subscription.remove();🎨 Example Use Cases
Voice Recording UI
function VoiceRecorder() {
const { isListening, audioLevel, start, stop, formattedTime } = useVoiceFrequency();
return (
<View>
<View style={styles.micContainer}>
<Icon name="microphone" />
</View>
<Text>{formattedTime}</Text>
<Text>
{audioLevel.isVoiceDetected ? 'Recording...' : 'Speak now'}
</Text>
<Button title="Stop" onPress={stop} />
</View>
);
}Voice Activity Indicator
function VoiceActivityIndicator() {
const { audioLevel } = useVoiceFrequency();
return (
<View style={{
width: 10,
height: 10,
borderRadius: 5,
backgroundColor: audioLevel.isVoiceDetected ? 'green' : 'red'
}} />
);
}Audio Level Meter
function AudioMeter() {
const { audioLevel } = useVoiceFrequency();
return (
<View style={styles.meterBackground}>
<View style={{
width: `${audioLevel.level * 100}%`,
height: '100%',
backgroundColor: 'blue'
}} />
</View>
);
}♿ Accessibility
The package includes built-in accessibility features:
- Screen reader announcements when recording starts/stops
- Announces when voice is detected
- Proper ARIA labels for all UI elements
- Keyboard navigation support
These work automatically when you use the useVoiceFrequency hook.
🔧 Troubleshooting
iOS: "Module not found"
Make sure you've run pod install:
cd ios && pod install && cd ..Android: "Module not registered"
- Clean the build:
cd android && ./gradlew clean && cd ..- Rebuild:
npx react-native run-androidPermission Denied
Make sure you've:
- Added permissions to
Info.plist(iOS) orAndroidManifest.xml(Android) - Requested permissions at runtime before calling
start()
No audio levels showing
- Test on a real device (not simulator/emulator)
- Check that microphone permissions are granted
- Verify the microphone is working in other apps
🤝 Contributing
Contributions are welcome! Please open an issue or submit a pull request.
Development Setup
# Clone the repo
git clone https://github.com/danny235/react-native-voice-frequency.git
cd react-native-voice-frequency
# Install dependencies
yarn install
# Run type checking
yarn typecheck📄 License
MIT © Daniel Barima
🙏 Acknowledgments
- Built with React Native
- Uses native audio APIs for optimal performance
- Inspired by the need for better voice UI in mobile apps
📞 Support
- 🐛 Report a bug
- 💡 Request a feature
- 📧 Email: [email protected]
Made with ❤️ by Daniel Barima
### 3. **Create LICENSE file**
**voice-frequency/LICENSE**:MIT License
Copyright (c) 2025 Daniel Barima
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
### 4. **Create .npmignore**
**voice-frequency/.npmignore**:Example app
example/
Tests
tests/ mocks/ *.test.ts *.test.tsx
Build artifacts
*.tgz .DS_Store node_modules/ *.log
IDE
.vscode/ .idea/
Git
.git/ .github/
CI
.circleci/ .travis.yml
Misc
coverage/ .env
