首页 文章

AVAudioPlayer Swift 3 没有播放声音[1]

提问于
浏览
1

这个问题在这里已有答案:

我将 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.
    }

}

1 回答

  • 12

    你需要将AVPlayer的声明移到 class-level。在方法中声明它们时,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.
        }
    
    }
    

相关问题