AVAudioPlayer Swift 3 not playing sound [duplicate]

瘦欲@ 提交于 2021-02-04 21:00:26

问题


I added the AVFoundation.framework to my project. In my project navigator I added the file "Horn.mp3", this is a sound of 1 second.

When a button is pressed (with a image of a horn) the sound should play, also should a label change it's text.

The label is changing it's text, but the sound isn't playing.

This is my code:

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:


You need to move the AVPlayer's declaration to class-level. AVPlayer can't play sounds when you declare them in methods.

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


}


来源:https://stackoverflow.com/questions/42748014/avaudioplayer-swift-3-not-playing-sound

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!