I'm trying to play a sound with AVAudioPlayer
but it won't work.
Edit 1: Still doesn't work.
Edit 2: This code works. My device was in silent mode.
import UIKit import AVFoundation class ViewController: UIViewController { var audioPlayer = AVAudioPlayer() override func viewDidLoad() { super.viewDidLoad() var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("button-09", ofType: "wav")) println(alertSound) var error:NSError? audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error) audioPlayer.prepareToPlay() audioPlayer.play() } }
An object that plays audio data from a file or buffer.
Made modification to your code:
import UIKit import AVFoundation class ViewController: UIViewController { var audioPlayer = AVAudioPlayer() override func viewDidLoad() { super.viewDidLoad() var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("button-09", ofType: "wav")) println(alertSound) // Removed deprecated use of AVAudioSessionDelegate protocol AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil) AVAudioSession.sharedInstance().setActive(true, error: nil) var error:NSError? audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error) audioPlayer.prepareToPlay() audioPlayer.play() } }
Swift 3 and Swift 4.1:
import UIKit import AVFoundation class ViewController: UIViewController { private var audioPlayer: AVAudioPlayer? override func viewDidLoad() { super.viewDidLoad() let alertSound = URL(fileURLWithPath: Bundle.main.path(forResource: "button-09", ofType: "wav")!) print(alertSound) try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) try! AVAudioSession.sharedInstance().setActive(true) try! audioPlayer = AVAudioPlayer(contentsOf: alertSound) audioPlayer!.prepareToPlay() audioPlayer!.play() } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With