AVAudioPlayer no longer works in Swift 2.0 / Xcode 7 beta

In the var testAudio in the iPhone app, I get an error here.

"A call may cause, but errors cannot be thrown from the property initializer"

 import UIKit import AVFoundation class ViewController: UIViewController { var testAudio = AVAudioPlayer(contentsOfURL: NSURL (fileURLWithPath: NSBundle.mainBundle().pathForResource("testAudio", ofType: "wav")!), fileTypeHint:nil) 

This happened when I switched to the beta version of Xcode 7.

How can I get this sound clip in Swift 2.0?

+6
source share
3 answers

Swift 2 has a completely new error handling system, you can read about it here: Swift 2 Error Handling .

In your case, the AVAudioPlayer constructor may AVAudioPlayer error. Swift will not allow you to use methods that cause errors in property initializers, because there is no way to handle them. Instead, do not initialize the property until the init view controller.

 var testAudio:AVAudioPlayer; init() { do { try testAudio = AVAudioPlayer(contentsOfURL: NSURL (fileURLWithPath: NSBundle.mainBundle().pathForResource("testAudio", ofType: "wav")!), fileTypeHint:nil) } catch { //Handle the error } } 

This gives you the ability to handle any errors that may occur when creating an audio player, and will stop Xcode by giving you warnings.

+21
source

If you know the error will not be returned, you can add try! in advance:

 testAudio = try! AVAudioPlayer(contentsOfURL: NSURL (fileURLWithPath: NSBundle.mainBundle().pathForResource 
+2
source

Works for me in Swift 2.2

But do not forget to add fileName.mp3 to the project. Build phases-> Copy Bundle resources (right-click on the project root).

 var player = AVAudioPlayer() func music() { let url:NSURL = NSBundle.mainBundle().URLForResource("fileName", withExtension: "mp3")! do { player = try AVAudioPlayer(contentsOfURL: url, fileTypeHint: nil) } catch let error as NSError { print(error.description) } player.numberOfLoops = 1 player.prepareToPlay() player.play() } 
+1
source

Source: https://habr.com/ru/post/988939/


All Articles