¿Cómo reproducir un sonido en Swift?

Me gustaría reproducir un sonido en Swift lo más simple posible.


Mi código funcionó en Swift 1.0, pero ahora ya no funciona en Swift 2 o posterior. Probé este código para reproducir música en MainMenuView :

 override func viewDidLoad() { super.viewDidLoad() let bgMusicURL:NSURL = NSBundle.mainBundle().URLForResource("Squart-MainMenu", withExtension: "mp3")! do { bgMusic = try AVAudioPlayer(contentsOfURL: bgMusicURL, fileTypeHint: nil) } catch _{ return print("no music file") } bgMusic.numberOfLoops = 1 bgMusic.prepareToPlay() if (Data.backgroundMenuPlayed == 0){ bgMusic.play() Data.backgroundMenuPlayed = 1 } } 

Siempre arroja el error "NO AUDIO PLAYER" y el file de música está en la carpeta principal, así que no creo que la ruta de música no sea accesible.

Lo más preferible es que desee usar AVFoundation . Proporciona todo lo esencial para trabajar con medios audiovisuales.

Actualización: Compatible con Swift 2 , Swift 3 y Swift 4 como lo sugieren algunos de ustedes en los comentarios.


Swift 2.3

 import AVFoundation var player: AVAudioPlayer? func playSound() { let url = NSBundle.mainBundle().URLForResource("soundName", withExtension: "mp3")! do { player = try AVAudioPlayer(contentsOfURL: url) guard let player = player else { return } player.prepareToPlay() player.play() } catch let error as NSError { print(error.description) } } 

Swift 3 y Swift 4

 import AVFoundation var player: AVAudioPlayer? func playSound() { guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return } do { try AVAudioSession.shanetworkingInstance().setCategory(AVAudioSessionCategoryPlayback) try AVAudioSession.shanetworkingInstance().setActive(true) player = try AVAudioPlayer(contentsOf: url) guard let player = player else { return } player.play() } catch let error { print(error.localizedDescription) } } 

Asegúrate de cambiar el nombre de tu melodía así como la extensión . El file debe importarse correctamente ( Project Build Phases > Copy Bundle Resources ). Es posible que desee colocarlo en assets.xcassets para mayor comodidad.


Para los files de sonido cortos, es posible que desee utilizar formattings de audio no comprimidos como .wav ya que tienen la mejor calidad y un bajo impacto de CPU. El mayor consumo de espacio en disco no debería ser un gran problema para los files de sonido cortos. Cuanto más largos sean los files, es posible que desee utilizar un formatting comprimido como .mp3 etc. pp. Compruebe los formattings de audio compatibles de CoreAudio .

Para Swift 3 :

 import AVFoundation /// **must** define instance variable outside, because .play() will deallocate AVAudioPlayer /// immediately and you won't hear a thing var player: AVAudioPlayer? func playSound() { guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { print("url not found") return } do { /// this codes for making this app ready to takeover the device audio try AVAudioSession.shanetworkingInstance().setCategory(AVAudioSessionCategoryPlayback) try AVAudioSession.shanetworkingInstance().setActive(true) /// change fileTypeHint according to the type of your audio file (you can omit this) player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) // no need for prepareToPlay because prepareToPlay is happen automatically when calling play() player!.play() } catch let error as NSError { print("error: \(error.localizedDescription)") } } 

La mejor práctica para los activos locales es ponerlo dentro de assets.xcassets y cargar el file de esta forma:

 func playSound() { guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { print("url not found") return } do { /// this codes for making this app ready to takeover the device audio try AVAudioSession.shanetworkingInstance().setCategory(AVAudioSessionCategoryPlayback) try AVAudioSession.shanetworkingInstance().setActive(true) /// change fileTypeHint according to the type of your audio file (you can omit this) /// for iOS 11 onward, use : player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue) /// else : /// player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) // no need for prepareToPlay because prepareToPlay is happen automatically when calling play() player!.play() } catch let error as NSError { print("error: \(error.localizedDescription)") } } 

Swift 3

import AVFoundation

 var myAudio: AVAudioPlayer! let path = Bundle.main.path(forResource: "example", ofType: "mp3")! let url = URL(fileURLWithPath: path) do { let sound = try AVAudioPlayer(contentsOf: url) myAudio = sound sound.play() } catch { // } //If you want to stop the sound, you should use its stop()method.if you try to stop a sound that doesn't exist your app will crash, so it's best to check that it exists. if myAudio != nil { myAudio.stop() myAudio = nil }