framework apple ios swift avfoundation

ios - framework - apple swift documentation



¿Cómo reproducir un sonido usando Swift? (14)

Me gustaría reproducir un sonido con Swift.

Mi código funcionó en Swift 1.0 pero ahora ya no funciona en Swift 2 o posterior.

override func viewDidLoad() { super.viewDidLoad() let url:NSURL = NSBundle.mainBundle().URLForResource("soundName", withExtension: "mp3")! do { player = try AVAudioPlayer(contentsOfURL: url, fileTypeHint: nil) } catch _{ return } bgMusic.numberOfLoops = 1 bgMusic.prepareToPlay() if (Data.backgroundMenuPlayed == 0){ player.play() Data.backgroundMenuPlayed = 1 } }


Estilo de juego:

archivo Sfx.swift

import AVFoundation var player:AVAudioPlayer! func Play(){ guard let path = Bundle.main.path(forResource: "KurdishSong", ofType: "mp3")else{return} let soundURl = URL(fileURLWithPath: path) player = try? AVAudioPlayer(contentsOf: soundURl) player.prepareToPlay() player.play() //player.pause() //player.stop() }

En cualquier lugar del código

sfx.explosion() sfx.cheer()


Swift 4 (compatible con iOS 12)

var player: AVAudioPlayer? let path = Bundle.main.path(forResource: "note/(sender.tag)", ofType: "wav") let url = URL(fileURLWithPath: path ?? "") do { player = try AVAudioPlayer(contentsOf: url) player?.play() } catch let error { print(error.localizedDescription) }


Código muy simple para veloz

agregue su archivo de audio a su Xcode y proporcione el código como se indica

import AVFoundation class ViewController: UIViewController{ var audioPlayer = AVAudioPlayer() //declare as Globally override func viewDidLoad() { super.viewDidLoad() guard let sound = Bundle.main.path(forResource: "audiofilename", ofType: "mp3") else { print("error to get the mp3 file") return } do { audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: sound)) } catch { print("audio file error") } audioPlayer.play() } @IBAction func notePressed(_ sender: UIButton) { //Button action audioPlayer.stop() }


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.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) try AVAudioSession.sharedInstance().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 archivo de esta manera:

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.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) try AVAudioSession.sharedInstance().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)") } }


Primero importe estas bibliotecas

import AVFoundation import AudioToolbox

establecer delegado como este

AVAudioPlayerDelegate

escribe este bonito código en la acción del botón o algo:

guard let url = Bundle.main.url(forResource: "ring", withExtension: "mp3") else { return } do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) try AVAudioSession.sharedInstance().setActive(true) player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue) guard let player = player else { return } player.play() }catch let error{ print(error.localizedDescription) }

100% trabajando en mi proyecto y probado


Probado con Swift 4 y iOS 12:

import UIKit import AVFoundation class ViewController: UIViewController{ var player: AVAudioPlayer! override func viewDidLoad() { super.viewDidLoad() } func playTone(number: Int) { let path = Bundle.main.path(forResource: "note/(number)", ofType : "wav")! let url = URL(fileURLWithPath : path) do { player = try AVAudioPlayer(contentsOf: url) print ("note/(number)") player.play() } catch { print (error) } } @IBAction func notePressed(_ sender: UIButton) { playTone(number: sender.tag) } }


Si el código no genera ningún error, pero no escucha ningún sonido, cree el reproductor como una instancia:

static var player: AVAudioPlayer!

Para mí, la primera solución funcionó cuando hice este cambio :)


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 }


iOS 12 - Xcode 10 beta 6 - Swift 4.2

Use solo 1 IBAction y apunte todos los botones a esa 1 acción.

import AVFoundation var player = AVAudioPlayer() @IBAction func notePressed(_ sender: UIButton) { print(sender.tag) // testing button pressed tag let path = Bundle.main.path(forResource: "note/(sender.tag)", ofType : "wav")! let url = URL(fileURLWithPath : path) do { player = try AVAudioPlayer(contentsOf: url) player.play() } catch { print ("There is an issue with this code!") } }


Lo más preferible es que desee utilizar AVFoundation . Proporciona todos los elementos esenciales 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

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

Swift 4 (compatible con iOS 12)

import AVFoundation var player: AVAudioPlayer? func playSound() { guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return } do { try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default) try AVAudioSession.sharedInstance().setActive(true) /* The following line is required for the player to work on iOS 11. Change the file type accordingly*/ player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue) /* iOS 10 and earlier require the following line: player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) */ guard let player = player else { return } player.play() } catch let error { print(error.localizedDescription) } }

Asegúrese de cambiar el nombre de su melodía, así como la extension . El archivo debe importarse correctamente ( Project Build Phases > Copy Bundle Resources ). Es posible que desee colocarlo en assets.xcassets para mayor comodidad.

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

Dato curioso: hay pequeñas bibliotecas ordenadas que hacen que la reproducción de sonidos sea aún más fácil. :)
Por ejemplo: SwiftySound


Swift 4, 4.2 y 5

Reproduzca audio desde la URL y desde su proyecto (archivo local)

import UIKit import AVFoundation class ViewController: UIViewController{ var audioPlayer : AVPlayer! override func viewDidLoad() { super.viewDidLoad() // call what ever function you want. } private func playAudioFromURL() { guard let url = URL(string: "https://geekanddummy.com/wp-content/uploads/2014/01/coin-spin-light.mp3") else { print("error to get the mp3 file") return } do { audioPlayer = try AVPlayer(url: url as URL) } catch { print("audio file error") } audioPlayer?.play() } private func playAudioFromProject() { guard let url = Bundle.main.url(forResource: "azanMakkah2016", withExtension: "mp3") else { print("error to get the mp3 file") return } do { audioPlayer = try AVPlayer(url: url) } catch { print("audio file error") } audioPlayer?.play() } }


func playSound(_ buttonTag : Int){ let path = Bundle.main.path(forResource: "note/(buttonTag)", ofType : "wav")! let url = URL(fileURLWithPath : path) do{ soundEffect = try AVAudioPlayer(contentsOf: url) soundEffect?.play() // to stop the spound .stop() }catch{ print ("file could not be loaded or other error!") } }

funciona en swift 4 última versión. ButtonTag sería una etiqueta en un botón en su interfaz. Las notas están en una carpeta en una carpeta paralela a Main.storyboard. Cada nota se nombra como nota1, nota2, etc. ButtonTag proporciona el número 1, 2, etc. del botón al que se hace clic y que se pasa como parámetro


import UIKit import AVFoundation class ViewController: UIViewController{ var player: AVAudioPlayer? override func viewDidLoad() { super.viewDidLoad() } @IBAction func notePressed(_ sender: UIButton) { guard let url = Bundle.main.url(forResource: "note1", withExtension: "wav") else { return } do { try AVAudioSession.sharedInstance().setCategory((AVAudioSession.Category.playback), mode: .default, options: []) try AVAudioSession.sharedInstance().setActive(true) /* The following line is required for the player to work on iOS 11. Change the file type accordingly*/ player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.wav.rawValue) /* iOS 10 and earlier require the following line: player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) *// guard let player = player else { return } player.play() } catch let error { print(error.localizedDescription) } } }


import AVFoundation var player:AVAudioPlayer! func Play(){ guard let path = Bundle.main.path(forResource: "KurdishSong", ofType: "mp3")else{return} let soundURl = URL(fileURLWithPath: path) player = try? AVAudioPlayer(contentsOf: soundURl) player.prepareToPlay() player.play() //player.pause() //player.stop() }