【问题标题】:Swift 3 - AVAudioPlayer is not playing soundSwift 3 - AVAudioPlayer 不播放声音
【发布时间】:2016-10-11 20:53:44
【问题描述】:

我有一个简单的程序,它只有一个按钮,唯一的功能是触发声音输出。

该应用程序在 iOS 模拟器上测试时运行良好,但当我在 iPhone 上测试时,该应用程序没有播放任何声音。我已经在两部 iPhone 上对此进行了测试。

这从前是有效的。我不知道更新到 iOS 10 是否导致了这个问题。

这是我的代码:

//Code
import UIKit
import AVFoundation

var audioPlayer = AVAudioPlayer()


class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.


        let music = Bundle.main.path(forResource: "sound", ofType: "wav")

        do {
            audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: music! ))
        }
        catch{
            print(error)
        }

    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func playSound(_ sender: UIButton) {

        audioPlayer.play()
    }

}

如果有任何答案,将不胜感激。 谢谢。

【问题讨论】:

  • 请检查您的 iPhone 音量(不是铃声)

标签: ios iphone swift audio swift3


【解决方案1】:
   override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.


        let music = Bundle.main.path(forResource: "sound", ofType: "wav")

        do {
            audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: music! ))
audioPlayer.delegate = self
audioPlayer.preparedToPlay()
        }
        catch{
            print(error)
        }

    }

【讨论】:

    【解决方案2】:
    import UIKit
    import AVFoundation
    
    class ViewController: UIViewController {
    
    var btnSound: AVAudioPlayer!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //locate resource
        let path = Bundle.main.path(forResource: "sound", ofType: "wav")
        let music = URL(fileURLWithPath: path!)
    
        do{
            try btnSound = AVAudioPlayer(contentsOf: music)
            btnSound.prepareToPlay()
        } catch let err as NSError{
            print(err.debugDescription)
        }
     }
    }
    
    func playSound(){
        if btnSound.isPlaying{
           //stop playing sound file if already playing
            btnSound.stop()
        }
        //play sound
        btnSound.play()
    }
    
    @IBAction func playSound(sender: UIButton){
        //call playSound function on pressing the button you attach this function to
        playSound()
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-10
      相关资源
      最近更新 更多