我将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, …Run Code Online (Sandbox Code Playgroud)