使用 Swift 2 的 AVFoundation 播放声音

Play Sound Using AVFoundation with Swift 2

我正在尝试使用 AVFoundation 在我的 iOS 应用程序(用 Swift 2 编写)中播放声音。我使用之前版本的 Swift 没有任何问题。我正在使用 Xcode 7.0。我不确定问题出在哪里,也找不到 Swift 2 关于播放声音的任何其他信息。这是我的声音部分代码:

import AVFoundation

class ViewController: UIViewController {
    var mySound = AVAudioPlayer()

    override func viewDidLoad() {
            super.viewDidLoad()
        mySound = self.setupAudioPlayerWithFile("mySound", type:"wav")

        mySound.play()
    }

    func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer  {
            var path = NSBundle.mainBundle().pathForResource(file, ofType:type)
            var url = NSURL.fileURLWithPath(path!)

            var error: NSError?

            var audioPlayer:AVAudioPlayer?
            audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)

            return audioPlayer!
    }
}

我收到此错误,但感觉可能还有其他问题:

'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?

您需要执行 try catch 错误处理。像这样尝试:

func setupAudioPlayerWithFile(file: String, type: String) -> AVAudioPlayer? {

    if let url = NSBundle.mainBundle().URLForResource(file, withExtension: type) {
        do {
            return try AVAudioPlayer(contentsOfURL: url)
        } catch let error as NSError {
            print(error.localizedDescription)
        }
    }
    return nil
}

就像狮子座说的那样

You need to implement do try catch error handling.

这是另一个代码示例,当按下按钮时会运行发出声音。

import UIKit
import AVFoundation

class ViewController: UIViewController {


@IBAction func play(sender: AnyObject) {

     player.play()

}

@IBAction func pause(sender: AnyObject) {

    player.pause()

}


var player: AVAudioPlayer = AVAudioPlayer()

override func viewDidLoad() {
    super.viewDidLoad()

    let audioPath = NSBundle.mainBundle().pathForResource("sound", ofType: "mp3")!

    do {

        try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath))


    } catch {

        // Process error here

    }


  }

}

希望对您有所帮助!