【发布时间】:2015-10-19 17:29:09
【问题描述】:
我一直在努力将一段用于录制音频的代码从 swift 1.2 更改为 swift 2。在这里的人们的帮助下,我做了一些更改,最终摆脱了所有编译器错误。但是现在,在我运行代码后,登录 Twitter,然后单击模拟器中的 Record 按钮,它崩溃并给我一个运行时错误。请看这里的图片:
另外,我不确定这是否重要,但我从代码中删除了“AVFormatIDKey : NSNumber(int: Int32(kAudioFormatAppleLossless))”并注释掉了“self.audioRecorder.meteringEnabled = true”和“ self.audioRecorder.prepareToRecord()" 从代码中,它不再崩溃,但显然这不是代码应该在最后运行的方式......
这是完整版的代码。对此有什么想法吗?
非常感谢您的帮助
import UIKit
import AVFoundation
class RecordViewController: UIViewController {
required init?(coder aDecoder: NSCoder) {
var baseString : String = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as String
self.audioURL = "sound.m4a"
var pathComponents = [baseString, self.audioURL]
var audioNSURL = NSURL.fileURLWithPathComponents(pathComponents)
var session = AVAudioSession.sharedInstance()
do {
try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
} catch (_) {
}
// session.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil)
// var recordSettings: [String : AnyObject] = Dictionary()
// recordSettings[AVFormatIDKey] = kAudioFormatMPEG4AAC
// recordSettings[AVFormatIDKey] = NSNumber(unsignedInt: kAudioFormatMPEG4AAC)
// recordSettings[AVSampleRateKey] = 44100.0
// recordSettings[AVNumberOfChannelsKey] = 2
let recordSettings = [
AVSampleRateKey : NSNumber(float: Float(44100.0)),
AVFormatIDKey : NSNumber(int: Int32(kAudioFormatAppleLossless)),
AVNumberOfChannelsKey : NSNumber(int: 1),
AVEncoderAudioQualityKey : NSNumber(int: Int32(AVAudioQuality.Medium.rawValue)),
AVEncoderBitRateKey : NSNumber(int: Int32(320000))
]
// self.audioRecorder = AVAudioRecorder(URL: audioNSURL, settings: recordSettings, error: nil)
self.audioRecorder = AVAudioRecorder()
print("aaaaa")
do {
self.audioRecorder = try AVAudioRecorder(URL: audioNSURL!, settings: recordSettings)
} catch (_) {
}
self.audioRecorder.meteringEnabled = true
self.audioRecorder.prepareToRecord()
super.init(coder: aDecoder)
}
// required init(coder aDecoder: NSCoder!) {
// super.init(coder : aDecoder)
// self.audioRecorder = AVAudioRecorder()
// }
@IBOutlet weak var recordButton: UIButton!
@IBOutlet weak var playButton: UIButton!
@IBOutlet weak var saveButton: UIBarButtonItem!
var audioRecorder : AVAudioRecorder
var audioURL = ""
override func viewDidLoad() {
super.viewDidLoad()
self.playButton.enabled = false
self.saveButton.enabled = false
// Do any additional setup after loading the view.
}
@IBAction func cancelTapped(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func saveTapped(sender: AnyObject) {
}
@IBAction func recordTapped(sender: AnyObject) {
self.playButton.enabled = true
}
@IBAction func playTapped(sender: AnyObject) {
}
}
【问题讨论】:
-
1- 不要强制解开
audioNSURL,在之前使用if let以保证它不为零。 2- 不要忽略catch块中的错误。 // 这应该足以解决您的问题——或者能够正确调试它们。
标签: ios swift avaudiorecorder