我一直在努力改變一段代碼,用於將音頻從swift 1.2錄製到swift 2.在這裏的人們的幫助下,我做了一些改變,最終擺脫了所有編譯器錯誤。但是現在,在我運行代碼之後,登錄到Twitter,然後單擊模擬器中的Record按鈕,它崩潰並給我一個運行時錯誤。請在這裏看到的畫面:Swift運行時錯誤(exc_bad_access)AVAudioRecorder,recordSettings
此外,我不知道這是很重要的或沒有,但我刪除從代碼「AVFormatIDKey::(的Int32(kAudioFormatAppleLossless)INT)的NSNumber」的評論從代碼中刪除「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',使用'如果let'之前,以保證它不是零。 2-不要忽略'catch'塊中的錯誤。 //它已經足以解決您的問題 - 或者能夠正確調試它們。 – Moritz