Swift File.read(into:)抛出“Foundation._GenericObjCError error 0”错误

cbjzeqam  于 11个月前  发布在  Swift
关注(0)|答案(2)|浏览(145)

我正在做一个项目,包括记录西瓜的砰砰声,并通过它产生的声音预测它的甜度。我使用AVAudioRecorder来记录和保存音频。但当我试图打开和读取文件时,它给了我一个错误(这个错误只发生在我在实际的iPhone XR上测试应用程序时,而不是在我使用xcode模拟器时)错误代码是:
“Foundation._GenericObjCError错误0”。
下面是录音功能和提取音频功能:

private func startRecording() {
        do {
            
            if self.record{
                // recording already started
                
                recorder.stop()
                self.record.toggle()
                // updating data for every recording
                self.getAudios()
                return
            }
            // record audio
            
            // store audio in document directory
//            var highPassFilter = AVAudioUnitEQFilterType.highPass
//            var lowPassFilter = AVAudioUnitEQFilterType.lowPass
            
            let fileURL: URL = {
                        let src = "thump.wav"
                        return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent(src)
                   }()
            
//            let fileURL : URL = {
//                return Bundle.main.url(forResource: "thump", withExtension: "wav")
//            }()!
            
            let recordSettings: [String : Any] = [AVFormatIDKey: Int(kAudioFormatLinearPCM),
                                                  AVSampleRateKey: 44100.0,
                                                  AVNumberOfChannelsKey: 1,
                                                  AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue ]
            
            self.recorder = try AVAudioRecorder(url: fileURL, settings: recordSettings)
            print(fileURL)
            self.recorder.record()
            print("Recording started")
            self.record.toggle()
        } catch {
            print(error.localizedDescription)
        }
    } 

func getAudios() {
        
        do {
            
            let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
            
            // Fetch all data from document directory
            
            let result = try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil, options: .producesRelativePathURLs)
            
            self.audios.removeAll()
            
            for i in result {
                
                self.audios.append(i)
                
            }
            
        }
        catch {
            print(error.localizedDescription)
        }
        
    }

字符串
这是我在file.read中获得错误的函数(into:buf):

func readAudioIntoFloats(fname: String, ext: String) -> [Float] {
            let interleaved: Bool = false
            
            let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
            let fileName = url.appendingPathComponent("\(fname).\(ext)")
//            let fileName = Bundle.main.url(forResource: "thump", withExtension: "wav")
            print(fileName)
            let file = try! AVAudioFile(forReading: fileName)
            let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: file.fileFormat.sampleRate, channels: file.fileFormat.channelCount, interleaved: interleaved)!

            let buf = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 4096*24)!
            do {
                try file.read(into: buf)
            } catch {
                print(error.localizedDescription)
            }
            
            var floatArray: [Float] = []

            if (Int(file.fileFormat.channelCount) == 2) {
                let leftArray = Array(UnsafeBufferPointer(start: buf.floatChannelData?[0], count:Int(buf.frameLength)))
                let rightArray = Array(UnsafeBufferPointer(start: buf.floatChannelData?[1], count:Int(buf.frameLength)))
                
                for i in 0..<leftArray.count {
                    floatArray.append((leftArray[i]+rightArray[i])/Float(2))
                }
            } else {
                
                floatArray = Array(UnsafeBufferPointer(start: buf.floatChannelData?[0], count:Int(buf.frameLength)))
                
            }
            
            print(floatArray.count)
            return floatArray

        }

cgyqldqp

cgyqldqp1#

更新:我通过将会话的类别设置为playandRecord来修复这个问题

gzszwxb4

gzszwxb42#

如果您使用AVAudioEngine(就像我的情况一样),请确保在尝试audioFile.read(into:audioFileBuffer)时它尚未运行

相关问题