2016-10-10 106 views
0

我正在创建一个音频录制框架,它被正确编译。当我在一个项目中使用这个框架时,录制文件将在框架中指定的文档文件夹中创建,但它的大小保持在4KB,并且不会增加,并且文件中没有音频。我给了30秒的记录时间。我已经使用AVFoundation进行录音,如果我直接在我的项目中使用AVFoundation,但是通过自定义创建的框架调用代码不起作用,那么代码将起作用。自定义录音机框架Swift 3.0

public func startRecording() { 
    do { 
     if (recordingSession != nil) { 
      return 
     } 
     recordingSession = AVAudioSession.sharedInstance() 
     try recordingSession.setCategory(AVAudioSessionCategoryPlayAndRecord) 
     try recordingSession.setActive(true) 

     recordingSession.requestRecordPermission() { allowed in 
      DispatchQueue.main.async { 
       if allowed { 
        print("allowed") 
        let audioFilename = self.getDocumentsDirectory().appendingPathComponent("recording.caf") 
        print(audioFilename) 
        let settings = [ 
         AVFormatIDKey: Int(kAudioFormatAppleIMA4), 
         AVSampleRateKey: 16000, 
         AVNumberOfChannelsKey: 1, 
         AVLinearPCMBitDepthKey: 16, 
         AVLinearPCMIsBigEndianKey: 0, 
         AVLinearPCMIsFloatKey: 0 
        ] 

        do { 
         self.audioRecorder = try AVAudioRecorder(url: audioFilename, settings: settings) 
         self.audioRecorder.delegate = self 
         self.audioRecorder.isMeteringEnabled = true 
         let audioHWAvailable = self.recordingSession.isInputAvailable 
         if !audioHWAvailable 
         { 
          print("no audio input available") 
          return 
         } 
         UIApplication.shared.beginReceivingRemoteControlEvents() 

         self.audioRecorder.record(forDuration: 30) 
         if self.audioRecorder.prepareToRecord() 
         { 
          print("Recording started") 
          self.audioRecorder.record() 
         } 

        } catch { 
         self.finishRecording() 
        } 
       } else { 
        print("failed to record!") 
       } 
      } 
     } 
    } catch { 
     print("failed to record!") 
    } 

} 

我在我的项目中调用了框架类中的startRecording方法。

编辑:当我在self.audioRecorder.record()行后添加计时器时,录制工作,但我不明白原因。

回答

0

最后,我通过Apple支持团队的帮助找到了解决方案。

通过使用AudioRecording类的全局变量对startRecording()进行调用,它无需添加计时器即可工作。