Zum Inhalt springen

Erste Schritte mit Audio Recorder

Diese Anleitung führt Sie durch die Integration des Capacitor Audio Recorder Plugins in Ihre Anwendung.

Installieren Sie das Plugin mit npm:

Terminal-Fenster
npm install @capgo/capacitor-audio-recorder
npx cap sync

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>

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" />

Das Plugin verwendet die MediaRecorder API. Erfordert HTTPS in der Produktion.

import { AudioRecorder } from '@capgo/capacitor-audio-recorder';
const requestPermission = async () => {
const permission = await AudioRecorder.requestPermissions();
console.log('Berechtigungsstatus:', permission.recordAudio);
};
const startRecording = async () => {
await AudioRecorder.startRecording();
console.log('Aufnahme gestartet');
};
const stopRecording = async () => {
const result = await AudioRecorder.stopRecording();
console.log('Aufnahmepfad:', result.filePath);
console.log('Dauer:', result.duration);
};
const pauseRecording = async () => {
await AudioRecorder.pauseRecording();
console.log('Aufnahme pausiert');
};
const resumeRecording = async () => {
await AudioRecorder.resumeRecording();
console.log('Aufnahme fortgesetzt');
};
const getStatus = async () => {
const status = await AudioRecorder.getStatus();
console.log('Nimmt auf:', status.isRecording);
console.log('Dauer:', status.currentTime);
};

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;
}
}
// Verwendung
const recorder = new VoiceRecorder();
// Initialisieren
await recorder.initialize();
// Aufnahme starten
await recorder.startRecording();
// Pausieren
await recorder.pauseRecording();
// Fortsetzen
await recorder.resumeRecording();
// Stoppen und Ergebnis abrufen
const result = await recorder.stopRecording();
console.log('Aufnahme gespeichert:', result?.filePath);
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
});
};
const startVoiceRecording = async () => {
await AudioRecorder.startRecording({
format: 'aac',
sampleRate: 16000, // 16 kHz (für Sprache optimiert)
channels: 1, // Mono
bitRate: 64000 // 64 kbps
});
};
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 initialisieren
const ui = new AudioRecorderUI();
ui.init();
  1. Berechtigungen frühzeitig anfordern: Prüfen Sie Berechtigungen, bevor Sie die Aufnahme-UI anzeigen
  2. Unterbrechungen behandeln: Telefonanrufe, Alarme können die Aufnahme unterbrechen
  3. Speicher verwalten: Alte Aufnahmen löschen, um Speicherplatz zu sparen
  4. Feedback geben: Aufnahmestatus, Dauer und Wellenform anzeigen
  5. Auf Geräten testen: Simulatoren/Emulatoren haben eingeschränkte Audio-Unterstützung
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.');
}
};
// App im Hintergrund behandeln
document.addEventListener('pause', async () => {
const status = await recorder.getCurrentStatus();
if (status.isRecording) {
await recorder.pauseRecording();
// Benutzer benachrichtigen
}
});
const cleanupOldRecordings = async () => {
// Bereinigungslogik implementieren
// Aufnahmen löschen, die älter als X Tage sind
// Oder nur die letzten N Aufnahmen behalten
};
  • 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