尝试使用AVFoundation播放声音

时间:2016-11-21 06:44:27

标签: swift xcode avfoundation

我对Xcode很新,因此如果下面需要一个简单的修复就道歉。创建了一个简单的按钮作为不同项目的测试,在"支持文件"下导入了mp3文件。目录和下面是我的代码,由于我遵循的教程,它们都使用不同版本的Xcode,这给出了一些错误。

AVFoundation也被添加到该项目中。

错误:

  

参数标签'(_:,错误:)'做 - 额外的争论'错误'在电话中   使用未解析的标识符' alertSound'

代码:

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var AudioPlayer = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let alertSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "two", ofType: "mp3")!)
        print(alertSound)

        AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
        AVAudioSession.sharedInstance().setActive(true, error: nil)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func n2(_ sender: UIButton) {

        var error:NSError?
        AudioPlayer = AVAudioPlayer(contentsOfUrl: alertSound, error: &error)
        AudioPlayer.prepareToPlay()
        AudioPlayer.play()
    }
}

1 个答案:

答案 0 :(得分:1)

第一个错误: 参数标签'(_:,错误:)'做 - 额外的争论'错误'在电话中

包含错误参数并返回布尔值的Objective C函数将被标记为可能在Swift 3中抛出异常的函数。您可以使用do..try..catch构造来处理错误。

您可以在此处查看有关错误处理的Apple文档: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html

与AudioPlayer变量相关的另一个错误是在范围之外访问的局部变量。

   var AudioPlayer = AVAudioPlayer()

// Declare alertSound at the instance level for use by other functions.
let alertSound = URL(fileURLWithPath: Bundle.main.path(forResource: "two", ofType: "mp3")!)

override func viewDidLoad() {
    super.viewDidLoad()

    print(alertSound)

    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)
    }
    catch {
        print("ERROR: \(error.localizedDescription)")
    }
}

@IBAction func n2(_ sender: UIButton) {

    do {
        AudioPlayer = try AVAudioPlayer(contentsOf: alertSound)
        AudioPlayer.prepareToPlay()
        AudioPlayer.play()
    }
    catch {
         print("ERROR: \(error.localizedDescription)")
    }
}