繁体   English   中英

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

[英]AVAudioPlayer no longer working in Swift 2.0 / Xcode 7 beta

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

“调用可以抛出,但错误不能从属性初始化程序中抛出”

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

当我转到Xcode 7测试版时,就发生了这种情况。

如何在Swift 2.0中使用此音频剪辑?

Swift 2有一个全新的错误处理系统,你可以在这里阅读更多相关内容: Swift 2错误处理

在您的情况下, 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
    }
}

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

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

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

适用于Swift 2.2

但是不要忘记将fileName.mp3添加到项目构建阶段 - >复制捆绑资源(右键单击项目根目录)

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

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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