AVAudioPlayer no longer working in Swift 2.0 / Xcode 7 beta

泪湿孤枕 提交于 2019-12-19 17:47:03

问题


For the var testAudio declaration in my iPhone app, I am receiving an error here

"Call can throw, but errors cannot be thrown out of a 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 moved to the Xcode 7 beta.

How can I get this audio clip functioning in Swift 2.0?


回答1:


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

In your case, the AVAudioPlayer constructor can throw an error. Swift won't let you use methods that throw errors in property initializers because there is no way to handle them there. Instead, don't initialize the property until the init of the 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 a chance to handle any errors that may come up when creating the audio player and will stop Xcode giving you warnings.




回答2:


If you know an error won't be returned you can add try! beforehand:

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



回答3:


Works for me in Swift 2.2

But don't forget to add the 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()

}


来源:https://stackoverflow.com/questions/30786877/avaudioplayer-no-longer-working-in-swift-2-0-xcode-7-beta

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!