AVAudioRecord 没有音频

问题描述 投票:0回答:0

我正在尝试一个简单的示例,使用 Swift 中的

AVAudoiRecorder
在 iOS 中录制音频,我创建了此类:

import Foundation
import AVFoundation

class AudioRecorder: NSObject, AVAudioRecorderDelegate {
    var audioRecorder: AVAudioRecorder?
    var file: URL? = nil
    
    func setupAudioSession() {
        let session = AVAudioSession.sharedInstance()
        
        do {
            try session.setCategory(.playAndRecord, mode: .default)
            try session.setActive(true)
            try session.overrideOutputAudioPort(.speaker)
            debugPrint("Listo todo")
        } catch {
            print("Error setting up audio session: \(error.localizedDescription)")
        }
    }
    
    func startRecording() {
        file = getDocumentsDirectory().appendingPathComponent("recording.wav")
        
        let settings: [String: Any] = [
            AVFormatIDKey: kAudioFormatLinearPCM,
            AVSampleRateKey: 44100.0,
            AVNumberOfChannelsKey: 2,
            AVLinearPCMBitDepthKey: 16,
            AVLinearPCMIsFloatKey: false,
            AVLinearPCMIsBigEndianKey: false
        ]
        
        do {
            audioRecorder = try AVAudioRecorder(url: file!, settings: settings)
            audioRecorder?.delegate = self
            audioRecorder?.prepareToRecord()
            audioRecorder?.record()
        } catch {
            print("Error starting recording: \(error.localizedDescription)")
        }
    }
    
    func stopRecording() {
        audioRecorder?.stop()
    }
    
    private func getDocumentsDirectory() -> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return paths[0]
    }
    
    // MARK: AVAudioRecorderDelegate
    func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
        if flag {
            print("Recording was successful.")
        } else {
            print("Recording failed.")
        }
    }
}

视图调用

setupAudioSession
,按下按钮时我调用
startRecording
(在此之前,我使用
AVAudioSession.sharedInstance().requestRecordPermission
检查麦克风权限)。

当我按下停止键时,我会在日志中收到来自

Recording was successful
回调的
audioRecorderDidFinishRecording
消息。如果我尝试使用
AVAudioPlayer
播放文件,我可以正确读取文件属性:

"Playing ... Optional(\"file:///var/mobile/Containers/Data/Application/0760DB3E-440E-4898-83A6-0888EC2EA399/Documents/recording.wav\")"
"Duration: 4.180997732426304"
"Format: <AVAudioFormat 0x281ce80f0:  2 ch,  44100 Hz, Int16, interleaved>"
"Current Time: 0.0"
"Volume: 1.0"

但是根本没有声音。我还在 Info.plist 中设置了

NSMicrophoneUsageDescription
来访问麦克风。

我已经在模拟器和真实设备中尝试过,但根本没有声音。另外,我已经下载了 WAV 文件并在音频编辑器中检查,该文件是空的。

知道我可能会错过什么吗?看起来像一个真正的例子,我能找到的所有搜索内容都非常相似。

ios swift avaudiorecorder
© www.soinside.com 2019 - 2024. All rights reserved.