gpt4 book ai didi

ios - Swift录音和tableview显示

转载 作者:行者123 更新时间:2023-11-28 06:53:30 25 4
gpt4 key购买 nike

我在录制音频并将其显示在表格 View 中时遇到问题。我能够录制并立即回放,但音频似乎并没有真正永久存储到设备中,所以我无法从 tableview 中调用它。每次打开应用程序时,目录似乎也会发生变化。在填充表格 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 - Swift录音和tableview显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34303976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com