Error in Formatting Recorded Audio

Asked 2 years ago, Updated 2 years ago, 29 views

When setting the audio format, the following programs will fail:

Note: I added UInt, but I get an error in as [NSObject:AnyObject] of soundRecorder.

let recordSettings: [String:Any] = [AVFormatIDKey:UInt(kAudioFormatAppleLossless),
    AVencoderAudioQualityKey: AVAudioQuality.Max.rawValue,
    AVencoderBitRateKey: 160000,
    AVNumberOfChannelsKey—2,
    AVSampleRateKey:8000.0]

variable error:NSError?

soundRecorder=AVAudioRecorder(URL:getFileURL(), settings:recordSettings as [NSObject:AnyObject], error:&error) // This is where the error occurs.

If anyone is aware of this, I would appreciate your guidance.

ios swift

2022-09-30 17:08

2 Answers

The code for the question before editing was OK with Xcode6, but now it's Xcode7/iOS9SDK and
kAudioFormatAppleLossless goes from Int to UInt32, and bits-specified numeric types such as UInt32 are not automatically converted to NSNumber, which results in an error.

Therefore, Xcode7 must explicitly convert to a AnyObject compatible type such as UInt.

If you leave it as it is, the recordSettings will be NSDictionary, so specify the [String:AnyObject] that the AVAudioRecorder initializer requests.

let recordSettings: String: AnyObject = [
    AVFormatIDKey: UInt (kAudioFormatAppleLossless), // < -- This
    AVencoderAudioQualityKey: AVAudioQuality.Max.rawValue,
    AVencoderBitRateKey: 160000,
    AVNumberOfChannelsKey—2,
    AVSampleRateKey—8000.0
]

NSNumber (unsingedInt:kAudioFormatAppleLossless) is fine, but
UInt has fewer characters.

Also, the AVAudioRecorder initializer is now throw, so you need to handle or ignore errors such as try.Swift error handling is not discussed here because it is different from the purpose of the question.


2022-09-30 17:08

Since the compiler is not able to infer the type, for example, specify the type: var recordSettings: [String:Any].

 var recordSettings: String: Any = AVFormatIDKey:kAudioFormatAppleLossless,
    AVencoderAudioQualityKey: AVAudioQuality.Max.rawValue,
    AVencoderBitRateKey: 160000,
    AVNumberOfChannelsKey—2,
    AVSampleRateKey:8000.0]


2022-09-30 17:08

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.