# Troubleshooting Guide

This guide helps you resolve common issues with the Cordova Audio Recorder Plugin.

## 🚨 Common Issues

### 1. "Failed to create audio recorder" Error

**Symptoms:**
- Error message: "Failed to create audio recorder" or "Failed to create audio recorder - initialization returned nil"
- Recording fails to start

**Causes:**
- Audio session not properly configured
- Invalid audio settings
- File path issues
- Permission problems

**Solutions:**

#### Step 1: Check Plugin Installation
```bash
# Verify plugin is installed
cordova plugin ls | grep audio-recorder

# Should show: cordova-plugin-audio-recorder
```

#### Step 2: Use Debug Test File
```bash
# Copy debug test file to your project
cp /Users/mccapplelaptop/Documents/PLUGINS/cordova-plugin-audio-recorder/debug-test.html www/

# Open debug-test.html in your app and check the logs
```

#### Step 3: Check Xcode Console
1. Open your project in Xcode
2. Run the app
3. Check the console for debug messages like:
   - "Creating audio recorder with file path: ..."
   - "Audio settings: ..."
   - "Audio recorder created successfully: ..."
   - "Audio recorder creation failed - returned nil"

#### Step 4: Verify Audio Session
Add this test to your app:
```javascript
// Test audio session setup
navigator.audioRecorder.checkPermission(
    function(permission) {
        console.log('Permission:', permission);
        if (permission === 'granted') {
            console.log('Permission granted, trying to record...');
        } else {
            console.log('Permission denied, requesting...');
            navigator.audioRecorder.requestPermission(
                function(result) {
                    console.log('Permission result:', result);
                },
                function(error) {
                    console.log('Permission error:', error);
                }
            );
        }
    },
    function(error) {
        console.log('Permission check error:', error);
    }
);
```

#### Step 5: Check Audio Settings
Try with minimal settings:
```javascript
navigator.audioRecorder.startRecording(
    function(result) {
        console.log('Success:', result);
    },
    function(error) {
        console.log('Error:', error);
    },
    {
        quality: 1,        // MEDIUM
        format: 'wav',
        sampleRate: 44100,
        channels: 1,
        fileName: 'test.wav'
    }
);
```

#### Step 6: Reinstall Plugin
```bash
# Complete reinstall
cordova plugin remove cordova-plugin-audio-recorder
cordova clean ios
cordova platform remove ios
cordova platform add ios
cordova plugin add /Users/mccapplelaptop/Documents/PLUGINS/cordova-plugin-audio-recorder
cordova build ios
```

### 2. "Duplicate Symbols" Error

**Symptoms:**
- Build fails with "duplicate symbols" error
- Multiple framework linking conflicts

**Solutions:**

#### Quick Fix
```bash
# Use the automated installation script
./install-conflict-free.sh
```

#### Manual Fix
1. Open your project in Xcode
2. Go to your target → Build Phases → Link Binary With Libraries
3. Remove duplicate `AVFoundation.framework` entries
4. Clean and rebuild

#### Alternative: Use No-Frameworks Version
```bash
# Replace plugin.xml with no-frameworks version
cp plugin-no-frameworks.xml plugin.xml
cordova plugin remove cordova-plugin-audio-recorder
cordova plugin add /Users/mccapplelaptop/Documents/PLUGINS/cordova-plugin-audio-recorder
```

### 3. "Module not found" Error

**Symptoms:**
- JavaScript error: "module cordova-plugin-audio-recorder.AudioRecorderConstants not found"
- Plugin methods not available

**Solutions:**

#### Reinstall Plugin
```bash
cordova plugin remove cordova-plugin-audio-recorder
cordova clean ios
cordova plugin add /Users/mccapplelaptop/Documents/PLUGINS/cordova-plugin-audio-recorder
```

#### Check JavaScript Loading
```javascript
// Test plugin loading
document.addEventListener('deviceready', function() {
    console.log('Device ready');
    
    if (typeof navigator.audioRecorder !== 'undefined') {
        console.log('✅ Plugin loaded');
        console.log('Methods:', Object.getOwnPropertyNames(navigator.audioRecorder));
    } else {
        console.log('❌ Plugin not loaded');
    }
}, false);
```

### 4. Permission Issues

**Symptoms:**
- "Microphone permission not granted" error
- Permission requests fail

**Solutions:**

#### Check Info.plist
Ensure your `Info.plist` contains:
```xml
<key>NSMicrophoneUsageDescription</key>
<string>This app needs access to microphone to record audio.</string>
```

#### Request Permission Manually
```javascript
navigator.audioRecorder.requestPermission(
    function(permission) {
        console.log('Permission:', permission);
    },
    function(error) {
        console.log('Error:', error);
    }
);
```

#### Check iOS Settings
1. Go to iOS Settings → Privacy & Security → Microphone
2. Ensure your app has microphone permission enabled

### 5. UI Threading Issues

**Symptoms:**
- "Main Thread Checker: UI API called on a background thread" errors
- UI becomes unresponsive/hangs
- Timer not working
- Stop recording tap not working
- "Calling -viewDidAppear: directly on a view controller is not supported" warnings

**Causes:**
- UI components being created on background threads
- Audio operations happening on wrong threads
- Main thread blocking

**Solutions:**

#### Step 1: Reinstall with Threading Fixes
```bash
# Reinstall the plugin with latest threading fixes
cordova plugin remove cordova-plugin-audio-recorder
cordova clean ios
cordova plugin add /Users/mccapplelaptop/Documents/PLUGINS/cordova-plugin-audio-recorder
cordova build ios
```

#### Step 2: Use Threading Test
```bash
# Copy threading test file
cp /Users/mccapplelaptop/Documents/PLUGINS/cordova-plugin-audio-recorder/threading-test.html www/

# Open threading-test.html in your app
```

#### Step 3: Check Main Thread Operations
Ensure all UI operations happen on the main thread:
```javascript
// Test UI responsiveness
document.addEventListener('deviceready', function() {
    console.log('Testing UI responsiveness...');
    
    // Test that UI remains responsive during audio operations
    navigator.audioRecorder.startRecording(
        function(result) {
            console.log('Recording started - UI should remain responsive');
            
            // Test UI responsiveness
            setTimeout(() => {
                console.log('UI responsiveness test passed');
            }, 1000);
        },
        function(error) {
            console.log('Recording error:', error);
        }
    );
}, false);
```

### 6. Build Errors

**Symptoms:**
- Xcode build fails
- Compilation errors

**Solutions:**

#### Clean Build
```bash
# Clean everything
cordova clean ios
cordova platform remove ios
cordova platform add ios
cordova build ios
```

#### Xcode Clean
1. Open project in Xcode
2. Product → Clean Build Folder
3. Build again

#### Check Dependencies
```bash
# Check Cordova version
cordova --version

# Check iOS platform version
cordova platform ls

# Should be:
# ios 6.2.0 (or higher)
```

## 🔍 Debug Information

### Enable Debug Logging
Add this to your app to get detailed logs:
```javascript
// Enable debug logging
if (typeof navigator.audioRecorder !== 'undefined') {
    console.log('Audio Recorder Plugin Debug Info:');
    console.log('- Available methods:', Object.getOwnPropertyNames(navigator.audioRecorder));
    console.log('- Quality settings:', navigator.audioRecorder.Quality);
    console.log('- Format settings:', navigator.audioRecorder.Format);
}
```

### Check Plugin Status
```javascript
// Comprehensive plugin check
function checkPluginStatus() {
    console.log('=== Plugin Status Check ===');
    
    // Check if plugin exists
    if (typeof navigator.audioRecorder !== 'undefined') {
        console.log('✅ Plugin loaded');
        
        // Check methods
        const methods = Object.getOwnPropertyNames(navigator.audioRecorder);
        console.log('Methods:', methods);
        
        // Check constants
        if (navigator.audioRecorder.Quality) {
            console.log('Quality constants:', navigator.audioRecorder.Quality);
        }
        if (navigator.audioRecorder.Format) {
            console.log('Format constants:', navigator.audioRecorder.Format);
        }
        
        // Test permission
        navigator.audioRecorder.checkPermission(
            function(permission) {
                console.log('✅ Permission:', permission);
            },
            function(error) {
                console.log('❌ Permission error:', error);
            }
        );
    } else {
        console.log('❌ Plugin not loaded');
    }
}

// Run check after device ready
document.addEventListener('deviceready', checkPluginStatus, false);
```

## 📞 Getting Help

If you're still experiencing issues:

1. **Check the debug logs** using the debug test file
2. **Review Xcode console** for native error messages
3. **Verify plugin installation** with `cordova plugin ls`
4. **Test with minimal settings** to isolate the issue
5. **Check iOS permissions** in Settings app

## ✅ Success Checklist

- [ ] Plugin installs without errors
- [ ] No "duplicate symbols" errors
- [ ] No "module not found" errors
- [ ] Plugin loads in JavaScript (`navigator.audioRecorder` exists)
- [ ] Permission request works
- [ ] Recording starts successfully
- [ ] Audio data is returned correctly
- [ ] Blob conversion works

---

**Note**: This plugin is designed to be conflict-free and should work with any existing Cordova project. If you continue to have issues, try the automated installation script which handles most common problems automatically.
