ios - 快速录音和桌面 View 显示

标签 ios swift audio avfoundation record

我在录制音频并将其显示在表格 View 中时遇到问题。我能够录制并立即播放它,但音频实际上似乎并未永久存储到设备中,因此我无法从桌面 View 中调用它。每次打开应用程序时,该目录似乎也会发生变化。在填充表格 View 行时,如何更正代码以实现永久保存和调用?

func record() {

    let audioSession:AVAudioSession = AVAudioSession.sharedInstance()

    if (audioSession.respondsToSelector("requestRecordPermission:")) {
        AVAudioSession.sharedInstance().requestRecordPermission({(granted: Bool)-> Void in
            if granted {
                print("granted")

                try! audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
                try! audioSession.setActive(true)

                let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
                let fullPath = (documentsDirectory as NSString).stringByAppendingPathComponent("Mobile.PCM")
                let url = NSURL.fileURLWithPath(fullPath)

                 print(fullPath)

                let settings: [String : AnyObject] = [
                    AVFormatIDKey:Int(kAudioFormatAppleIMA4), 
                    AVSampleRateKey:44100.0,
                    AVNumberOfChannelsKey:2,
                    AVEncoderBitRateKey:12800,
                    AVLinearPCMBitDepthKey:16,
                    AVEncoderAudioQualityKey:AVAudioQuality.Max.rawValue
                ]

                try! self.audioRecorder = AVAudioRecorder(URL: url, settings: settings)
                self.audioRecorder.meteringEnabled = true
                self.audioRecorder.record()

            } else{
                print("not granted")
            }
        })
    }

}

最佳答案

我可以用这个来记录和保存:

@IBAction func record(sender: UIButton) {

    if player != nil && player.playing {
        player.stop()
    }

    if recorder == nil {
        print("recording. recorder nil")
       // recordButton.setTitle("Pause", forState:.Normal)
        playButton.enabled = false
        stopButton.enabled = true
        recordWithPermission(true)
        return
    }

    if recorder != nil && recorder.recording {
        print("pausing")
        recorder.pause()
        recordButton.setTitle("Continue", forState:.Normal)

    } else {
        print("recording")
      //  recordButton.setTitle("Pause", forState:.Normal)
        playButton.enabled = false
        stopButton.enabled = true
        recordWithPermission(false)
    }
}

func setupRecorder() {
    let format = NSDateFormatter()
    format.dateFormat="yyyy-MM-dd-HH-mm-ss"
    let currentFileName = "recording-\(format.stringFromDate(NSDate())).caf"
    print(currentFileName)

    let documentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
     self.soundFileURL = documentsDirectory.URLByAppendingPathComponent(currentFileName)

    if NSFileManager.defaultManager().fileExistsAtPath(soundFileURL.absoluteString) {
        print("soundfile \(soundFileURL.absoluteString) exists")
    }

    let recordSettings:[String : AnyObject] = [
        AVFormatIDKey: NSNumber(unsignedInt:kAudioFormatAppleLossless),
        AVEncoderAudioQualityKey : AVAudioQuality.Max.rawValue,
        AVEncoderBitRateKey : 320000,
        AVNumberOfChannelsKey: 2,
        AVSampleRateKey : 44100.0
    ]

    do {
        recorder = try AVAudioRecorder(URL: soundFileURL, settings: recordSettings)
        recorder.delegate = self
        recorder.meteringEnabled = true
        recorder.prepareToRecord() soundFileURL
    } catch let error as NSError {
        recorder = nil
        print(error.localizedDescription)
    }

}

func recordWithPermission(setup:Bool) {
    let session:AVAudioSession = AVAudioSession.sharedInstance()
    if (session.respondsToSelector("requestRecordPermission:")) {
        AVAudioSession.sharedInstance().requestRecordPermission({(granted: Bool)-> Void in
            if granted {
                print("Permission to record granted")
                self.setSessionPlayAndRecord()
                if setup {
                    self.setupRecorder()
                }
                self.recorder.record()
                self.meterTimer = NSTimer.scheduledTimerWithTimeInterval(0.1,
                    target:self,
                    selector:"updateAudioMeter:",
                    userInfo:nil,
                    repeats:true)
            } else {
                print("Permission to record not granted")
            }
        })
    } else {
        print("requestRecordPermission unrecognized")
    }
}

我可以通过以下方式在 TableView 中调用它:

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.reloadData()
    listRecordings()
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell: UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell")!
    cell.textLabel!.text = recordings[indexPath.row].lastPathComponent
    return cell
}

func listRecordings() {

    let documentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
    do {
        let urls = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(documentsDirectory, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles)
        self.recordings = urls.filter( { (name: NSURL) -> Bool in
            return name.lastPathComponent!.hasSuffix("caf")
        })

    } catch let error as NSError {
        print(error.localizedDescription)
    } catch {
        print("something went wrong")
    } 
}

关于ios - 快速录音和桌面 View 显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34303976/

相关文章:

ios - 如何从 CoreDate 加载我的数据以在 tableView 中显示它?

iOS 模拟器版本没有出现 - Xcode 12.2

Python:与 winsound.Beep 最接近的 Linux 和 OSX 等价物是什么?

c++ - 我如何将控制映射到它的设备?

ios - tableview 中的这个空白区域是什么?

ios - 带有变量 Swift 的 NSLocalizedString

swift - CallKit :- Callkit is working but the callee doesn't get the call

bash - 如何合并列表中同一行上出现的所有WAV文件?

ios - 在 CoreData 中使用 Swift 的日期

ios - 我可以将 WidgetKit 扩展添加到目标 iOS < 14 的应用程序吗?