# Audio Recorder Plugin - Interval Recording Feature

This document describes the new `recordWithInterval` function added to the cordova-plugin-audio-recorder.

## Overview

The `recordWithInterval` function allows you to record audio for a specified duration and automatically returns the recorded audio as base64 data with its MIME type. This is useful for applications that need to record audio for a fixed period without manual start/stop controls.

## Features

- **Automatic Duration Control**: Records for exactly the specified duration
- **Base64 Output**: Returns audio data as base64 string for easy transmission
- **MIME Type Detection**: Automatically determines and returns the correct MIME type
- **Multiple Formats**: Supports M4A (AAC), WAV, and CAF formats
- **Quality Settings**: Configurable audio quality (Low, Medium, High)
- **Customizable Parameters**: Sample rate, channels, and filename options

## API Reference

### `recordWithInterval(successCallback, errorCallback, options)`

Records audio for a specified duration and returns the result.

#### Parameters

- **successCallback** (Function): Called when recording completes successfully
- **errorCallback** (Function): Called when recording fails
- **options** (Object): Recording configuration options

#### Options Object

| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `duration` | number | **Required** | Recording duration in seconds (1-300) |
| `quality` | number | 1 | Audio quality: 0=Low, 1=Medium, 2=High |
| `format` | string | 'm4a' | Audio format: 'm4a', 'wav', 'caf' |
| `sampleRate` | number | 44100 | Sample rate in Hz |
| `channels` | number | 1 | Number of channels: 1=Mono, 2=Stereo |
| `fileName` | string | auto-generated | Custom filename for the recording |

#### Success Callback Response

The success callback receives an object with the following properties:

```javascript
{
    audioData: "base64_encoded_audio_string",
    audioBlob: "data:audio/mp4;base64,base64_encoded_audio_string",
    filePath: "/path/to/recorded/file.m4a",
    duration: 5.2,
    fileSize: 12345,
    format: "m4a",
    mimeType: "audio/mp4"
}
```

## Usage Examples

### Basic Usage

```javascript
navigator.audioRecorder.recordWithInterval(
    function(result) {
        console.log('Recording completed!');
        console.log('Duration:', result.duration, 'seconds');
        console.log('File size:', result.fileSize, 'bytes');
        console.log('MIME type:', result.mimeType);
        console.log('Base64 data:', result.audioData);
        
        // Use the audio data
        const audioBlob = result.audioBlob;
        // or send the base64 data to a server
        sendToServer(result.audioData, result.mimeType);
    },
    function(error) {
        console.error('Recording failed:', error);
    },
    {
        duration: 10,  // Record for 10 seconds
        quality: 1,    // Medium quality
        format: 'm4a'  // M4A format
    }
);
```

### Advanced Usage with Custom Settings

```javascript
navigator.audioRecorder.recordWithInterval(
    function(result) {
        // Handle successful recording
        console.log('High-quality recording completed');
        
        // Create an audio element to play the recording
        const audio = new Audio(result.audioBlob);
        audio.play();
    },
    function(error) {
        console.error('Recording failed:', error);
    },
    {
        duration: 30,           // 30 seconds
        quality: 2,             // High quality
        format: 'm4a',          // M4A format
        sampleRate: 48000,      // 48kHz sample rate
        channels: 2,            // Stereo
        fileName: 'my_recording.m4a'
    }
);
```

### Sending to Server

```javascript
navigator.audioRecorder.recordWithInterval(
    function(result) {
        // Send the base64 audio data to your server
        fetch('/api/upload-audio', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                audioData: result.audioData,
                mimeType: result.mimeType,
                duration: result.duration,
                fileName: result.fileName
            })
        })
        .then(response => response.json())
        .then(data => console.log('Upload successful:', data))
        .catch(error => console.error('Upload failed:', error));
    },
    function(error) {
        console.error('Recording failed:', error);
    },
    {
        duration: 15,
        quality: 1,
        format: 'm4a'
    }
);
```

## Supported Formats and MIME Types

| Format | MIME Type | Description |
|--------|-----------|-------------|
| m4a | audio/mp4 | AAC encoded audio (recommended) |
| wav | audio/wav | Uncompressed WAV format |
| caf | audio/x-caf | Core Audio Format |

## Quality Settings

| Quality Level | Bit Rate | Use Case |
|---------------|----------|----------|
| 0 (Low) | 64 kbps | Voice recordings, limited bandwidth |
| 1 (Medium) | 128 kbps | General purpose (default) |
| 2 (High) | 256 kbps | Music, high-quality audio |

## Error Handling

Common error scenarios and their solutions:

### Permission Denied
```javascript
// Always check permission before recording
navigator.audioRecorder.checkPermission(
    function(status) {
        if (status === 'granted') {
            // Proceed with recording
        } else {
            // Request permission
            navigator.audioRecorder.requestPermission();
        }
    }
);
```

### Invalid Duration
```javascript
// Duration must be between 1 and 300 seconds
if (duration < 1 || duration > 300) {
    console.error('Invalid duration. Must be between 1 and 300 seconds.');
    return;
}
```

### Already Recording
```javascript
// Check if already recording
navigator.audioRecorder.getRecordingState(
    function(state) {
        if (state.state === 'recording') {
            console.log('Already recording. Wait for completion.');
        } else {
            // Start new recording
        }
    }
);
```

## Platform Support

- **iOS**: Full support with native AVAudioRecorder
- **Android**: Not implemented in this version
- **Browser**: Limited support (may not work in all browsers)

## Installation

1. Add the plugin to your Cordova project:
```bash
cordova plugin add cordova-plugin-audio-recorder
```

2. For iOS, ensure you have the following in your `config.xml`:
```xml
<platform name="ios">
    <config-file target="Info.plist" parent="NSMicrophoneUsageDescription">
        <string>This app requires Microphone to record audio</string>
    </config-file>
</platform>
```

## Testing

Use the provided `interval-recording-example.html` file to test the functionality:

1. Add the example file to your `www` directory
2. Open it in your Cordova app
3. Configure the recording parameters
4. Click "Start Recording" to test the interval recording

## Troubleshooting

### Recording Doesn't Start
- Check microphone permissions
- Ensure the device is not in silent mode
- Verify that no other app is using the microphone

### Poor Audio Quality
- Increase the quality setting (0-2)
- Use a higher sample rate (44100 or 48000 Hz)
- Ensure the device microphone is not covered

### Large File Sizes
- Use a lower quality setting
- Reduce the sample rate
- Use mono instead of stereo

### Base64 Data Issues
- Check that the MIME type is correct for your use case
- Ensure the base64 string is properly encoded
- Verify the data length matches the file size

## License

This plugin is licensed under the Apache License, Version 2.0.
