繁体   English   中英

Swift 3 - AVAudioPlayer 没有播放声音

[英]Swift 3 - AVAudioPlayer is not playing sound

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

该应用程序在 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()
    }

}

将不胜感激任何答案。 谢谢。

   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)
        }

    }
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()
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM