Getting Started with Audio Recorder
Konten ini belum tersedia dalam bahasa Anda.
This guide will walk you through integrating the Capacitor Audio Recorder plugin into your application.
Installation
Section titled âInstallationâInstall the plugin using npm:
npm install @capgo/capacitor-audio-recordernpx cap synciOS Configuration
Section titled âiOS ConfigurationâAdd the following to your Info.plist:
<key>NSMicrophoneUsageDescription</key><string>This app needs access to the microphone to record audio</string>Android Configuration
Section titled âAndroid ConfigurationâAdd the following permissions to your AndroidManifest.xml:
<uses-permission android:name="android.permission.RECORD_AUDIO" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />Web Configuration
Section titled âWeb ConfigurationâThe plugin uses the MediaRecorder API. Requires HTTPS in production.
Basic Usage
Section titled âBasic UsageâImport the Plugin
Section titled âImport the Pluginâimport { AudioRecorder } from '@capgo/capacitor-audio-recorder';Request Permissions
Section titled âRequest Permissionsâconst requestPermission = async () => { const permission = await AudioRecorder.requestPermissions(); console.log('Permission status:', permission.recordAudio);};Start Recording
Section titled âStart Recordingâconst startRecording = async () => { await AudioRecorder.startRecording(); console.log('Recording started');};Stop Recording
Section titled âStop Recordingâconst stopRecording = async () => { const result = await AudioRecorder.stopRecording(); console.log('Recording path:', result.filePath); console.log('Duration:', result.duration);};Pause/Resume Recording
Section titled âPause/Resume Recordingâconst pauseRecording = async () => { await AudioRecorder.pauseRecording(); console.log('Recording paused');};
const resumeRecording = async () => { await AudioRecorder.resumeRecording(); console.log('Recording resumed');};Get Status
Section titled âGet Statusâconst getStatus = async () => { const status = await AudioRecorder.getStatus(); console.log('Is recording:', status.isRecording); console.log('Duration:', status.currentTime);};Complete Example
Section titled âComplete ExampleâHereâs a complete voice recorder implementation:
import { AudioRecorder } from '@capgo/capacitor-audio-recorder';
class VoiceRecorder { private isRecording = false; private isPaused = false; private recordingPath: string | null = null;
async initialize() { const permission = await AudioRecorder.checkPermissions();
if (permission.recordAudio !== 'granted') { const requested = await AudioRecorder.requestPermissions();
if (requested.recordAudio !== 'granted') { throw new Error('Microphone permission denied'); } } }
async startRecording() { try { await AudioRecorder.startRecording(); this.isRecording = true; this.isPaused = false; console.log('Recording started'); } catch (error) { console.error('Failed to start recording:', error); throw error; } }
async pauseRecording() { if (!this.isRecording || this.isPaused) { return; }
try { await AudioRecorder.pauseRecording(); this.isPaused = true; console.log('Recording paused'); } catch (error) { console.error('Failed to pause recording:', error); throw error; } }
async resumeRecording() { if (!this.isRecording || !this.isPaused) { return; }
try { await AudioRecorder.resumeRecording(); this.isPaused = false; console.log('Recording resumed'); } catch (error) { console.error('Failed to resume recording:', error); throw error; } }
async stopRecording() { if (!this.isRecording) { return null; }
try { const result = await AudioRecorder.stopRecording(); this.isRecording = false; this.isPaused = false; this.recordingPath = result.filePath;
console.log('Recording stopped'); console.log('File path:', result.filePath); console.log('Duration:', result.duration, 'seconds');
return result; } catch (error) { console.error('Failed to stop recording:', error); throw error; } }
async getCurrentStatus() { const status = await AudioRecorder.getStatus(); return { isRecording: status.isRecording, duration: status.currentTime, isPaused: this.isPaused }; }
formatDuration(seconds: number): string { const mins = Math.floor(seconds / 60); const secs = Math.floor(seconds % 60); return `${mins}:${secs.toString().padStart(2, '0')}`; }
getRecordingPath(): string | null { return this.recordingPath; }}
// Usageconst recorder = new VoiceRecorder();
// Initializeawait recorder.initialize();
// Start recordingawait recorder.startRecording();
// Pauseawait recorder.pauseRecording();
// Resumeawait recorder.resumeRecording();
// Stop and get resultconst result = await recorder.stopRecording();console.log('Recording saved:', result?.filePath);Advanced Configuration
Section titled âAdvanced ConfigurationâConfigure Audio Quality
Section titled âConfigure Audio Qualityâconst startHighQualityRecording = async () => { await AudioRecorder.startRecording({ format: 'aac', // aac, mp3, or wav sampleRate: 44100, // 44100 Hz (CD quality) channels: 2, // Stereo bitRate: 320000 // 320 kbps });};Configure for Voice
Section titled âConfigure for Voiceâconst startVoiceRecording = async () => { await AudioRecorder.startRecording({ format: 'aac', sampleRate: 16000, // 16 kHz (voice optimized) channels: 1, // Mono bitRate: 64000 // 64 kbps });};UI Integration Example
Section titled âUI Integration Exampleâclass AudioRecorderUI { private recorder: VoiceRecorder; private updateInterval: any;
constructor() { this.recorder = new VoiceRecorder(); }
async init() { await this.recorder.initialize(); this.setupEventListeners(); }
setupEventListeners() { const recordButton = document.getElementById('record-btn'); const pauseButton = document.getElementById('pause-btn'); const stopButton = document.getElementById('stop-btn');
recordButton?.addEventListener('click', () => this.handleRecord()); pauseButton?.addEventListener('click', () => this.handlePause()); stopButton?.addEventListener('click', () => this.handleStop()); }
async handleRecord() { await this.recorder.startRecording(); this.startDurationUpdate(); this.updateUI('recording'); }
async handlePause() { const status = await this.recorder.getCurrentStatus();
if (status.isPaused) { await this.recorder.resumeRecording(); this.updateUI('recording'); } else { await this.recorder.pauseRecording(); this.updateUI('paused'); } }
async handleStop() { const result = await this.recorder.stopRecording(); this.stopDurationUpdate(); this.updateUI('stopped');
if (result) { this.showRecordingResult(result); } }
startDurationUpdate() { this.updateInterval = setInterval(async () => { const status = await this.recorder.getCurrentStatus(); this.updateDurationDisplay(status.duration); }, 100); }
stopDurationUpdate() { if (this.updateInterval) { clearInterval(this.updateInterval); } }
updateDurationDisplay(duration: number) { const display = document.getElementById('duration'); if (display) { display.textContent = this.recorder.formatDuration(duration); } }
updateUI(state: 'recording' | 'paused' | 'stopped') { // Update button states, colors, etc. console.log('UI state:', state); }
showRecordingResult(result: any) { console.log('Recording complete:', result); // Show playback UI, save options, etc. }}
// Initialize UIconst ui = new AudioRecorderUI();ui.init();Best Practices
Section titled âBest Practicesâ- Request Permissions Early: Check permissions before showing recording UI
- Handle Interruptions: Phone calls, alarms can interrupt recording
- Manage Storage: Clean up old recordings to save space
- Provide Feedback: Show recording status, duration, and waveform
- Test on Devices: Simulators/emulators have limited audio support
Common Issues
Section titled âCommon IssuesâPermission Denied
Section titled âPermission Deniedâconst handlePermissionDenied = async () => { const permission = await AudioRecorder.checkPermissions();
if (permission.recordAudio === 'denied') { alert('Microphone permission is required to record audio. Please enable it in Settings.'); }};Recording Interrupted
Section titled âRecording Interruptedâ// Handle app going to backgrounddocument.addEventListener('pause', async () => { const status = await recorder.getCurrentStatus(); if (status.isRecording) { await recorder.pauseRecording(); // Notify user }});Storage Management
Section titled âStorage Managementâconst cleanupOldRecordings = async () => { // Implement cleanup logic // Delete recordings older than X days // Or keep only last N recordings};Next Steps
Section titled âNext Stepsâ- Explore the API Reference for complete method documentation
- Check out the example app for advanced usage
- See the tutorial for complete implementation examples