iPhone设备能否同时进行音频录制与视频播放?技术问询
Hey there! This is absolutely achievable—you just need to work with iOS's audio session system correctly, since the default behavior prioritizes playback over recording, which is why your recording cuts out when the video starts.
Here's how to make it work:
1. Configure the AVAudioSession Properly
iOS uses audio sessions to manage how apps interact with the device's audio hardware. To enable both playback and recording at the same time, you need to set the session category to AVAudioSessionCategoryPlayAndRecord, plus specific options to allow audio mixing and route video sound to the speaker (so it doesn't default to the earpiece):
import AVFoundation func setupDualAudioSession() { let audioSession = AVAudioSession.sharedInstance() do { // Set category to support both playback and recording try audioSession.setCategory( .playAndRecord, mode: .default, options: [.mixWithOthers, .defaultToSpeaker] ) // Activate the session try audioSession.setActive(true) } catch { print("Failed to configure audio session: \(error.localizedDescription)") } }
2. Handle Required Permissions
You can't record audio without user permission. Add this key to your app's Info.plist with a clear explanation for users:
NSMicrophoneUsageDescription: "We need microphone access to record ambient audio while playing your video"
3. Make Sure Your Video Player Doesn't Hijack the Session
If you're using AVPlayer for video playback, double-check it doesn't override your audio session settings:
- Avoid setting
allowsExternalPlaybacktotrueunless you specifically need it, as this can alter audio routing - Listen for
AVAudioSessionInterruptionNotificationto handle unexpected session disruptions (like a phone call) and reactivate your session afterward if needed
4. Test Edge Cases
- If you're using a third-party video player library, check its docs to confirm it supports audio session mixing
- On older iOS versions, you may need to handle audio route changes (e.g., when headphones are plugged in) to maintain both playback and recording
Once you have these pieces in place, your app should be able to play video through the speaker while simultaneously capturing ambient audio from the microphone.
内容的提问来源于stack exchange,提问作者MRR

