簡體   English   中英

快速的音頻記錄和表格視圖顯示

[英]Swift audio recording and tableview display

我在錄制音頻並將其顯示在表格視圖中時遇到麻煩。 我可以錄制並立即播放,但是音頻似乎並沒有真正永久存儲到設備,因此無法從tableview調用它。 每次打開應用程序時,目錄似乎也會更改。 填充tableview行時,如何為永久保存和調用而更正代碼?

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")
    } 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM