AVAudioPlayer 不再适用于 Swift 2.0 / Xcode 7 beta

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30786877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 07:16:11  来源:igfitidea点击:

AVAudioPlayer no longer working in Swift 2.0 / Xcode 7 beta

iosxcodebetaxcode7

提问by Yaranaika

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

对于var testAudio我的 iPhone 应用程序中的声明,我在这里收到一个错误

"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.

当我转向 Xcode 7 beta 时发生了这种情况。

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

我怎样才能让这个音频剪辑在 Swift 2.0 中运行?

回答by SeanA

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

Swift 2 有一个全新的错误处理系统,你可以在这里阅读更多关于它的信息:Swift 2 错误处理

In your case, the AVAudioPlayerconstructor 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 initof the view controller.

在您的情况下,AVAudioPlayer构造函数可能会引发错误。Swift 不允许你使用在属性初始化器中抛出错误的方法,因为在那里没有办法处理它们。相反,init在视图控制器的之前不要初始化属性。

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.

这使您有机会处理在创建音频播放器时可能出现的任何错误,并停止 Xcode 向您发出警告。

回答by avance

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

如果您知道不会返回错误,则可以添加 try! 预先:

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

回答by Amir Twito

Works for me in Swift 2.2

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

但是不要忘记将fileName.mp3添加到项目Build Phases->Copy Bundle Resources(右键单击项目根目录)

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

}