快速的音频记录和表格视图显示 [英] Swift audio recording and tableview display

查看:61
本文介绍了快速的音频记录和表格视图显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法录制音频并将其显示在表格视图中.我可以录制并立即播放,但是音频似乎并没有真正永久存储到设备,因此无法从tableview调用它.每次打开应用程序时,目录似乎也会更改.填充表格视图行时,如何为永久保存和调用而更正代码?

I am having trouble recording audio and displaying it in a tableview. I am able to record and immediately play it back, but the audio doesn't seem to actually be stored to the device permanently, so I am unable to call it from the tableview. The directory also seems to change each time the app is open. How can I correct my code for permanent save and recall when populating tableview rows?

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

}

推荐答案

我可以用以下方式记录和保存:

I am able to record and save with this:

@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中调用它:

I am able to recall it in a TableView with this:

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

这篇关于快速的音频记录和表格视图显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆