按钮没有播放声音.我已经包含了wav文件



按钮不播放声音?
如何使代码更正确?

import UIKit
import AVFoundation
//var  audioPlayer: AVAudioPlayer!
class ViewController: UIViewController {
    var  audioPlayer: AVAudioPlayer!

    override func viewDidLoad() {
      super.viewDidLoad()
        let path =  Bundle.main.path(forResource: "BtnSon", ofType: " WAV")
        let soundURL = URL(fileURLWithPath: (path)!)
        do {
            try audioPlayer = AVAudioPlayer(contentsOf: soundURL)
          audioPlayer.prepareToPlay()
        } catch let err as NSError {
            print(err.debugDescription)
        }
    }
    @IBAction  func numberPressed(Sender: UIButton){
          playSound()
    }
    func playSound(){
        if audioPlayer.isPlaying {
          audioPlayer.stop()
        }
        audioPlayer.play()
    }
}

试试这个:

import UIKit
import UIKit
import AVFoundation
//var  audioPlayer: AVAudioPlayer!
class ViewController: UIViewController {
    var  audioPlayer: AVAudioPlayer!
    override func viewDidLoad() {
        super.viewDidLoad()
        //--------------------------------------------------------> No space before _W
        guard let soundURL =  Bundle.main.url(forResource: "BtnSon", withExtension: "WAV") else {
            fatalError("You have failed to add 'BtnSon.WAV' in your app bundle.")
        }
        do {
            try audioPlayer = AVAudioPlayer(contentsOf: soundURL)
            audioPlayer.prepareToPlay()
        } catch let err as NSError {
            print(err.debugDescription)
        }
    }
    @IBAction func numberPressed(_ sender: UIButton){
        playSound()
    }
    func playSound(){
        if audioPlayer.isPlaying {
            audioPlayer.stop()
        }
        audioPlayer.play()
    }
}

注意,iOS的文件系统是区分大小写的。

最新更新