Erste Schritte mit Audio Recorder
Diese Anleitung führt Sie durch die Integration des Capacitor Audio Recorder Plugins in Ihre Anwendung.
Installation
Section titled “Installation”Installieren Sie das Plugin mit npm:
npm install @capgo/capacitor-audio-recordernpx cap synciOS-Konfiguration
Section titled “iOS-Konfiguration”Fügen Sie Folgendes zu Ihrer Info.plist hinzu:
<key>NSMicrophoneUsageDescription</key><string>Diese App benötigt Zugriff auf das Mikrofon, um Audio aufzunehmen</string>Android-Konfiguration
Section titled “Android-Konfiguration”Fügen Sie die folgenden Berechtigungen zu Ihrer AndroidManifest.xml hinzu:
<uses-permission android:name="android.permission.RECORD_AUDIO" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />Web-Konfiguration
Section titled “Web-Konfiguration”Das Plugin verwendet die MediaRecorder API. Erfordert HTTPS in der Produktion.
Grundlegende Verwendung
Section titled “Grundlegende Verwendung”Plugin importieren
Section titled “Plugin importieren”import { AudioRecorder } from '@capgo/capacitor-audio-recorder';Berechtigungen anfordern
Section titled “Berechtigungen anfordern”const requestPermission = async () => { const permission = await AudioRecorder.requestPermissions(); console.log('Berechtigungsstatus:', permission.recordAudio);};Aufnahme starten
Section titled “Aufnahme starten”const startRecording = async () => { await AudioRecorder.startRecording(); console.log('Aufnahme gestartet');};Aufnahme stoppen
Section titled “Aufnahme stoppen”const stopRecording = async () => { const result = await AudioRecorder.stopRecording(); console.log('Aufnahmepfad:', result.filePath); console.log('Dauer:', result.duration);};Aufnahme pausieren/fortsetzen
Section titled “Aufnahme pausieren/fortsetzen”const pauseRecording = async () => { await AudioRecorder.pauseRecording(); console.log('Aufnahme pausiert');};
const resumeRecording = async () => { await AudioRecorder.resumeRecording(); console.log('Aufnahme fortgesetzt');};Status abrufen
Section titled “Status abrufen”const getStatus = async () => { const status = await AudioRecorder.getStatus(); console.log('Nimmt auf:', status.isRecording); console.log('Dauer:', status.currentTime);};Vollständiges Beispiel
Section titled “Vollständiges Beispiel”Hier ist eine vollständige Implementierung eines Sprachrekorders:
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('Mikrofonberechtigung verweigert'); } } }
async startRecording() { try { await AudioRecorder.startRecording(); this.isRecording = true; this.isPaused = false; console.log('Aufnahme gestartet'); } catch (error) { console.error('Aufnahme konnte nicht gestartet werden:', error); throw error; } }
async pauseRecording() { if (!this.isRecording || this.isPaused) { return; }
try { await AudioRecorder.pauseRecording(); this.isPaused = true; console.log('Aufnahme pausiert'); } catch (error) { console.error('Aufnahme konnte nicht pausiert werden:', error); throw error; } }
async resumeRecording() { if (!this.isRecording || !this.isPaused) { return; }
try { await AudioRecorder.resumeRecording(); this.isPaused = false; console.log('Aufnahme fortgesetzt'); } catch (error) { console.error('Aufnahme konnte nicht fortgesetzt werden:', 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('Aufnahme gestoppt'); console.log('Dateipfad:', result.filePath); console.log('Dauer:', result.duration, 'Sekunden');
return result; } catch (error) { console.error('Aufnahme konnte nicht gestoppt werden:', 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; }}
// Verwendungconst recorder = new VoiceRecorder();
// Initialisierenawait recorder.initialize();
// Aufnahme startenawait recorder.startRecording();
// Pausierenawait recorder.pauseRecording();
// Fortsetzenawait recorder.resumeRecording();
// Stoppen und Ergebnis abrufenconst result = await recorder.stopRecording();console.log('Aufnahme gespeichert:', result?.filePath);Erweiterte Konfiguration
Section titled “Erweiterte Konfiguration”Audioqualität konfigurieren
Section titled “Audioqualität konfigurieren”const startHighQualityRecording = async () => { await AudioRecorder.startRecording({ format: 'aac', // aac, mp3 oder wav sampleRate: 44100, // 44100 Hz (CD-Qualität) channels: 2, // Stereo bitRate: 320000 // 320 kbps });};Für Sprache konfigurieren
Section titled “Für Sprache konfigurieren”const startVoiceRecording = async () => { await AudioRecorder.startRecording({ format: 'aac', sampleRate: 16000, // 16 kHz (für Sprache optimiert) channels: 1, // Mono bitRate: 64000 // 64 kbps });};UI-Integrationsbeispiel
Section titled “UI-Integrationsbeispiel”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') { // Button-Zustände, Farben usw. aktualisieren console.log('UI-Status:', state); }
showRecordingResult(result: any) { console.log('Aufnahme abgeschlossen:', result); // Wiedergabe-UI, Speicheroptionen usw. anzeigen }}
// UI initialisierenconst ui = new AudioRecorderUI();ui.init();Best Practices
Section titled “Best Practices”- Berechtigungen frühzeitig anfordern: Prüfen Sie Berechtigungen, bevor Sie die Aufnahme-UI anzeigen
- Unterbrechungen behandeln: Telefonanrufe, Alarme können die Aufnahme unterbrechen
- Speicher verwalten: Alte Aufnahmen löschen, um Speicherplatz zu sparen
- Feedback geben: Aufnahmestatus, Dauer und Wellenform anzeigen
- Auf Geräten testen: Simulatoren/Emulatoren haben eingeschränkte Audio-Unterstützung
Häufige Probleme
Section titled “Häufige Probleme”Berechtigung verweigert
Section titled “Berechtigung verweigert”const handlePermissionDenied = async () => { const permission = await AudioRecorder.checkPermissions();
if (permission.recordAudio === 'denied') { alert('Mikrofonberechtigung ist erforderlich, um Audio aufzunehmen. Bitte aktivieren Sie sie in den Einstellungen.'); }};Aufnahme unterbrochen
Section titled “Aufnahme unterbrochen”// App im Hintergrund behandelndocument.addEventListener('pause', async () => { const status = await recorder.getCurrentStatus(); if (status.isRecording) { await recorder.pauseRecording(); // Benutzer benachrichtigen }});Speicherverwaltung
Section titled “Speicherverwaltung”const cleanupOldRecordings = async () => { // Bereinigungslogik implementieren // Aufnahmen löschen, die älter als X Tage sind // Oder nur die letzten N Aufnahmen behalten};Nächste Schritte
Section titled “Nächste Schritte”- Erkunden Sie die API-Referenz für vollständige Methodendokumentation
- Sehen Sie sich die Beispiel-App für erweiterte Verwendung an
- Siehe das Tutorial für vollständige Implementierungsbeispiele