Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Playing a sound with AVAudioPlayer

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()     } } 
like image 224
user3722523 Avatar asked Jun 24 '14 18:06

user3722523


People also ask

What is Avaudioplayer?

An object that plays audio data from a file or buffer.


1 Answers

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()     } } 
like image 82
vladof81 Avatar answered Sep 28 '22 06:09

vladof81