Reproducción de sonido con AVAudioPlayer

AVAudioPlayer reproducir un sonido con AVAudioPlayer pero no funcionará.

Edición 1: todavía no funciona.

Edición 2 : Este código funciona. Mi dispositivo estaba en modo silencioso.

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

Modificado su código:

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

Según Swift 2, el código debería ser

 var audioPlayer : AVAudioPlayer! func playSound(soundName: String) { let coinSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(soundName, ofType: "m4a")!) do{ audioPlayer = try AVAudioPlayer(contentsOfURL:coinSound) audioPlayer.prepareToPlay()//there is also an async version audioPlayer.play() }catch { print("Error getting the audio file") } } 

Su reproducción de audio será desasignada inmediatamente después de que viewDidLoad finalice ya que lo asigna a una variable local. Necesita crear una propiedad para mantenerlo.

La solución es para AudioPlayer que tiene el botón reproducir / pausar / detener en la barra de navegación como elementos de botón de barra

En Swift 2.1 puedes usar el siguiente código

 import UIKit import AVFoundation class ViewController: UIViewController { var player:AVAudioPlayer = AVAudioPlayer() override func viewDidLoad() { super.viewDidLoad() let audioPath = NSBundle.mainBundle().pathForResource("ARRehman", ofType: "mp3") var error:NSError? = nil do { player = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath!)) } catch { print("Something bad happened. Try catching specific errors to narrow things down") } } @IBAction func play(sender: UIBarButtonItem) { player.play() } @IBAction func stop(sender: UIBarButtonItem) { player.stop() print(player.currentTime) player.currentTime = 0 } @IBAction func pause(sender: UIBarButtonItem) { player.pause() } @IBOutlet weak var sliderval: UISlider! @IBAction func slidermov(sender: UISlider) { player.volume = sliderval.value print(player.volume) } } 

Esto funcionará …..

 import UIKit import AVFoundation class ViewController: UIViewController { var ding:AVAudioPlayer = AVAudioPlayer() override func viewDidLoad() { super.viewDidLoad() prepareAudios() ding.play() } func prepareAudios() { var path = NSBundle.mainBundle().pathForResource("ding", ofType: "mp3") ding = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path!), error: nil) ding.prepareToPlay() } } 

Use esta función para hacer sonido en Swift (Puede usar esta función donde desee hacer sonido).

Primero, agregue SpriteKit y AVFoundation Framework.

 import SpriteKit import AVFoundation func playEffectSound(filename: String){ runAction(SKAction.playSoundFileNamed("\(filename)", waitForCompletion: false)) }// use this function to play sound playEffectSound("Sound File Name With Extension") // Example :- playEffectSound("BS_SpiderWeb_CollectEgg_SFX.mp3") 

Esta es una pregunta muy antigua, pero no vi una respuesta que funcionara con Swift 3.0, así que modernicé el código y agregué algunos controles de seguridad para evitar lockings.

También tomé el enfoque de llevar la parte de juego a su propia función para ayudar con la reutilización para cualquier persona que encuentre esta respuesta.

 import UIKit import AVFoundation class ViewController: UIViewController { var audioPlayer: AVAudioPlayer? override func viewDidLoad() { super.viewDidLoad() play(for: "button-09", type: "wav") } func play(for resource: String, type: String) { // Prevent a crash in the event that the resource or type is invalid guard let path = Bundle.main.path(forResource: resource, ofType: type) else { return } // Convert path to URL for audio player let sound = URL(fileURLWithPath: path) do { audioPlayer = try AVAudioPlayer(contentsOf: sound) audioPlayer?.prepareToPlay() audioPlayer?.play() } catch { // Create an assertion crash in the event that the app fails to play the sound assert(false, error.localizedDescription) } } } 

Swift 4.2 en adelante, las opciones de configuración de la categoría AudioSession se han cambiado. (Intente seguir el código para Swift 4.2 en adelante)

 import UIKit import AVFoundation class ViewController: UIViewController { var audioPlayer: AVAudioPlayer? override func viewDidLoad() { super.viewDidLoad() prepareAudioSession() } func prepareAudioSession() -> Void { do { try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: AVAudioSession.Mode.default, options: AVAudioSession.CategoryOptions.defaultToSpeaker) try AVAudioSession.sharedInstance().setActive(true) prepareAudioPlayer() } catch { print("Issue with Audio Session") } } func prepareAudioPlayer() -> Void { let audioFileName = "test" let audioFileExtension = "mp3" guard let filePath = Bundle.main.path(forResource: audioFileName, ofType: audioFileExtension) else { print("Audio file not found at specified path") return } let alertSound = URL(fileURLWithPath: filePath) try? audioPlayer = AVAudioPlayer(contentsOf: alertSound) audioPlayer?.prepareToPlay() } func playAudioPlayer() -> Void { audioPlayer?.play() } func pauseAudioPlayer() -> Void { if audioPlayer?.isPlaying ?? false { audioPlayer?.pause() } } func stopAudioPlayer() -> Void { if audioPlayer?.isPlaying ?? false { audioPlayer?.stop() } } func resetAudioPlayer() -> Void { stopAudioPlayer() audioPlayer?.currentTime = 0 playAudioPlayer() } }