2017-03-12 203 views
1

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


} 
+0

您需要逐步執行playSound()在調試方法,看看它的一部分失敗 –

+0

我已經做到了,但每一步似乎工作。它不會跳過零件,而是走正確的路線。 – Stefan

回答

8

你需要移動AVPlayer的聲明類級別。 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. 
    } 


} 
+0

我的老師說這將是有效的把它放在我的功能,但感謝這個工程。 – Stefan

+1

哦,當然。問題是你需要保持對音頻播放器的強烈參考。當你使用局部變量時,當函數超出範圍並且音頻播放器被釋放時,強引用會消失。您可以將音頻播放器定義爲實例變量。這將解決弱參考問題。 –

+0

我一直在編程iOS 1900年,我完全忘了這麼做!謝謝! – Fattie