[英]Swift 3 - AVAudioPlayer is not playing sound
I have a simple program which has one button and its only function is to trigger an sound output.我有一个简单的程序,它只有一个按钮,它的唯一功能是触发声音输出。
The app works perfectly when tested on an iOS simulator, but when I test it on an iPhone, the app is not playing any sound.该应用程序在 iOS 模拟器上测试时完美运行,但当我在 iPhone 上测试时,该应用程序没有播放任何声音。 I have tested this on two iPhones.我已经在两部 iPhone 上对此进行了测试。
This was working once upon a time.这曾经是有效的。 I don't know if updating to iOS 10 has caused the issue.我不知道更新到 iOS 10 是否导致了这个问题。
Here is my code:这是我的代码:
//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()
}
}
Would be grateful for any answers.将不胜感激任何答案。 Thanks.谢谢。
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.