Reputation: 45
I was doing a tutorial and I tested this code, it works when I run on the emulator but when I test on the iPhone it can't. I debugged and he makes no mistake, just doesn't play the sound.
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate {
var audioPlayer = AVAudioPlayer()
@IBAction func notePressed(_ sender: UIButton) {
playSound(tag: sender.tag)
}
func playSound(tag: Int) {
let soundURL = Bundle.main.url(forResource: "note\(tag)", withExtension: "wav")
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundURL!)
} catch {
print(error)
}
audioPlayer.numberOfLoops = -1
audioPlayer.prepareToPlay()
audioPlayer.play()
}
}
Upvotes: 1
Views: 57
Reputation: 56
You have to set AVAudioSession.sharedInstance().setCategory(.playback)
before play audio
Upvotes: 4