简体   繁体   中英

swift2 AVAudioRecorder

I am trying the following code using swift 2, which should be fine in swift 1.

class NewSoundViewController: UIViewController {
required init(coder aDecoder: NSCoder) {
    let audioURL = NSURL.fileURLWithPathComponents([
        NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0],
        "MyAudio.m4a"
    ])
    do {
        let session = AVAudioSession.sharedInstance()
        try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
    } catch {
        print("Session errors.")
    }

    do {
        let recordSettings: [String: AnyObject] = [
            AVFormatIDKey: kAudioFormatMPEG4AAC,
            AVSampleRateKey: 44100.0,
            AVNumberOfChannelsKey: 2,
        ]
        self.audioRecorder = try AVAudioRecorder(URL: audioURL!, settings: recordSettings)
        self.audioRecorder.meteringEnabled = true
        self.audioRecorder.prepareToRecord()

    } catch let error as NSError{
        print(error.description)
    } catch {
        print("Other errors")            
    }
    super.init(coder: aDecoder)
}

I got compiling error

Type 'AudioFormatID' does not conform to protocol 'AnyObject'`

at the line AVFormatIDKey: kAudioFormatMPEG4AAC, .

If I comment out the line, I passed build, but got a runtime error

Error Domain=NSOSStatusErrorDomain Code=1718449215 "The operation couldn't be completed. (OSStatus error 1718449215.)"

I also tried AVFormatIDKey: NSNumber(unsignedInt: kAudioFormatMPEG4AAC), , and got runtime error. Xcode seemed go to debug mode It red highlighted self.audioRecorder = try AVAudioRecorder(URL: audioURL!, settings: recordSettings) and said

Thread 1: EXC_BAD_ACCESS(code=1, address=0x0)

Can anyone please help me?

I also tried AVFormatIDKey: NSNumber(unsignedInt: kAudioFormatMPEG4AAC)

Well, that is the correct thing to say. Basically you are asking two questions here; the compiler error you've already solved. Now you're having a runtime error, but that's completely different matter.

As for the runtime error, it's probably just a figment of trying to test on the Simulator. I ran your code on the device (after fixing the line in question so that it would compile) and it's fine.

EDIT In a comment, you revealed that you tested this on a device running iOS 8.3. That's the problem! You need to test on a device, and it needs to be a device running iOS 9. Then you'll find that your code runs without crashing.

I had the same issue with the settings. AVFormatIDKey was not accepted with the error mentioned in the original post.

The recordSettings needs to be explicitly casted in Swift 2.

These are my settings for recording that works. If I just skipped the AVFormatIDKey, the microphone only worked for a fraction of a second.

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))]

You don't need to upgrade the device to iOS 9. I built and ran this for iOS 8.4

I had a similar issue and it turns out that when I updated from swift 1.2 to 2.0 the signature of "settings" changed to a non optional [String : AnyObject]

//Swift 1.2
AVAudioRecorder(URL: audioURL!, settings: nil)

if I pass an empty dictionary it doesn't crash for me anymore and works as before.

//Swift 2.0    
AVAudioRecorder(URL: audioURL!, settings: [:])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM