AVAudioPlayer Swift 3 不播放声音

AVAudioPlayer Swift 3 not playing sound

我将 AVFoundation.framework 添加到我的项目中。在我的项目导航器中,我添加了文件 "Horn.mp3",这是 1 秒的声音。

按下按钮(带有喇叭图像)时应播放声音,标签也应更改其文本。

标签正在更改其文本,但没有播放声音。

这是我的代码:

import UIKit
import AVFoundation

class ViewController: UIViewController {

    @IBAction func hornButtonPressed(_ sender: Any) {
        playSound()
        hornLabel.text = "Toet!!!"
    }

    @IBOutlet weak var hornLabel: UILabel!

    func playSound(){
        var player: AVAudioPlayer?
        let sound = Bundle.main.url(forResource: "Horn", withExtension: "mp3")
        do {
            player = try AVAudioPlayer(contentsOf: sound!)
            guard let player = player else { return }
            player.prepareToPlay()
            player.play()
        } catch let error {
            print(error.localizedDescription)
        }

    }

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

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


}

您需要将 AVPlayer 的声明移动到 class 级别。 AVPlayer 在方法中声明时无法播放声音。

class ViewController: UIViewController {
    var player: AVAudioPlayer? // <-- notice here

    @IBAction func hornButtonPressed(_ sender: Any) {
        playSound()
        hornLabel.text = "Toet!!!"
    }

    @IBOutlet weak var hornLabel: UILabel!

    func playSound(){
        let sound = Bundle.main.url(forResource: "Horn", withExtension: "mp3")
        do {
            player = try AVAudioPlayer(contentsOf: sound!)
            guard let player = player else { return }
            player.prepareToPlay()
            player.play()
        } catch let error {
            print(error.localizedDescription)
        }

    }

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

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


}