Код:
Код: Выделить всё
import React, { useState, useEffect } from 'react';
import {
SafeAreaView,
View,
Text,
TouchableOpacity,
Alert
} from 'react-native';
import * as Audio from 'expo-audio';
import { CustomHeader } from '../components/CustomHeader';
import { colors } from '../constants/colors';
import { styles } from '../styles/styles';
export const MicrophoneSpeakerTest = ({ navigation }) => {
const [permissionsGranted, setPermissionsGranted] = useState(false);
const [isRecording, setIsRecording] = useState(false);
// Simple recorder setup
const recorder = Audio.useAudioRecorder({
extension: '.m4a',
audioQuality: Audio.AudioQuality?.HIGH || 'high',
});
useEffect(() => {
setupPermissions();
}, []);
const setupPermissions = async () => {
try {
console.log('Setting audio mode...');
await Audio.setAudioModeAsync({
allowsRecordingIOS: true,
playsInSilentModeIOS: true,
});
console.log('Requesting permissions...');
const permission = await Audio.requestRecordingPermissionsAsync();
console.log('Permission result:', permission);
setPermissionsGranted(permission.granted);
} catch (error) {
console.error('Setup error:', error);
Alert.alert('Setup Error', error.message);
}
};
const testMicrophone = async () => {
if (!permissionsGranted) {
Alert.alert('No Permission', 'Microphone permission not granted');
return;
}
try {
if (isRecording) {
console.log('Stopping recording...');
await recorder.stop();
setIsRecording(false);
Alert.alert('Recording Stopped', 'Did you see the orange light disappear?');
} else {
console.log('Starting recording...');
await recorder.record();
setIsRecording(true);
Alert.alert(
'Recording Started!',
'Is microphone active?'
);
}
} catch (error) {
console.error('Recording error:', error);
Alert.alert('Recording Error', error.message);
setIsRecording(false);
}
};
return (
{/* Permission Status */}
Permission: {permissionsGranted ? '✅ Granted' : '❌ Denied'}
{/* Simple Test Button */}
{isRecording ? '🔴 STOP Recording' : '🎤 START Recording'}
{isRecording
? 'Recording active! Look for orange light at top of screen.'
: 'Press the button to test if microphone activates (orange light appears).'
}
{permissionsGranted && (
Retry Setup
)}
);
};
Код: Выделить всё
Setting audio mode...
Requesting permissions...
Permission result: {"canAskAgain": true, "expires": "never", "granted": true, "status": "granted"}
Starting recording...
ERROR Recording error: [Error: FunctionCallException: Calling the 'record' function has failed (at ExpoModulesCore/SyncFunctionDefinition.swift:137)
→ Caused by: RecordingDisabledException: Recording not allowed on iOS. Enable with Audio.setAudioModeAsync (at ExpoAudio/AudioRecorder.swift:104)]
Код: Выделить всё
await Audio.setAudioModeAsync({
allowsRecording: true,
playsInSilentMode: true,
useAudioRecorder: true,
useAudioRecorderState:true,
allowsRecordingIos: true,
playsInSilentModeIos: true, // Optional: Allows playback even when the device is in silent mode
shouldDuckAndroid: true, // Optional: Lowers other audio sources on Android during playback
interruptionModeAndroid: Audio.INTERRUPTION_MODE_ANDROID_DO_NOT_MIX, // Optional: Defines how audio interacts with other audio sources on Android
interruptionModeIos: Audio.INTERRUPTION_MODE_IOS_DO_NOT_MIX, // Optional: Defines how audio interacts with other audio sources on iOS
});
Изменить: я только что попробовал этот же код на эмуляторе Android, как и iOS, он запрашивает разрешения и точно показывает, было ли оно предоставлено или нет, но на самом деле он не активирует микрофон (он также включен в настройках эмулятора). На Android ошибок не возникает.
Подробнее здесь: https://stackoverflow.com/questions/797 ... s-to-start
Мобильная версия