我將AVFoundation.framework添加到了我的項目中。在我的項目導航器中,我添加了文件「Horn.mp3」,這是一秒鐘的聲音。AVAudioPlayer Swift 3不播放聲音
當按下按鈕(帶有喇叭圖像)時,聲音應該播放,標籤也應該改變它的文本。
該標籤正在改變它的文本,但聲音沒有播放。
這是我的代碼:
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.
}
}
您需要逐步執行playSound()在調試方法,看看它的一部分失敗 –
我已經做到了,但每一步似乎工作。它不會跳過零件,而是走正確的路線。 – Stefan