Creando y reproduciendo un sonido en forma rápida

Entonces, lo que quiero hacer es crear y reproducir un sonido rápido que toque cuando presiono un botón, sé cómo hacerlo en Objective-C, pero ¿alguien sabe cómo hacerlo en Swift?

Sería así para Objective-C:

NSURL *soundURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"mysoundname" ofType:@"wav"]]; AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundURL, &mySound); 

Y luego para jugarlo haría:

 AudioServicesPlaySystemSound(Explosion); 

¿Alguien sabe cómo podría hacer esto?

Aquí hay un poco de código que he agregado a FlappySwift que funciona:

 import SpriteKit import AVFoundation class GameScene: SKScene { // Grab the path, make sure to add it to your project! var coinSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "coin", ofType: "wav")!) var audioPlayer = AVAudioPlayer() // Initial setup override func didMoveToView(view: SKView) { audioPlayer = AVAudioPlayer(contentsOfURL: coinSound, error: nil) audioPlayer.prepareToPlay() } // Trigger the sound effect when the player grabs the coin func didBeginContact(contact: SKPhysicsContact!) { audioPlayer.play() } } 

Esto es similar a algunas otras respuestas, pero tal vez un poco más “Swifty”:

 // Load "mysoundname.wav" if let soundURL = Bundle.main.url(forResource: "mysoundname", withExtension: "wav") { var mySound: SystemSoundID = 0 AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound) // Play AudioServicesPlaySystemSound(mySound); } 

Tenga en cuenta que este es un ejemplo trivial que reproduce el efecto del código en la pregunta. Tendrá que asegurarse de import AudioToolbox , además el patrón general para este tipo de código sería cargar sus sonidos cuando se inicie su aplicación, guardarlos en variables de instancia de SystemSoundID en alguna parte, usarlos en toda la aplicación y luego llamar a AudioServicesDisposeSystemSoundID cuando has terminado con ellos.

Extensión Handy Swift:

 import AudioToolbox extension SystemSoundID { static func playFileNamed(fileName: String, withExtenstion fileExtension: String) { var sound: SystemSoundID = 0 if let soundURL = NSBundle.mainBundle().URLForResource(fileName, withExtension: fileExtension) { AudioServicesCreateSystemSoundID(soundURL, &sound) AudioServicesPlaySystemSound(sound) } } } 

Luego, desde cualquier lugar de su aplicación (recuerde import AudioToolbox ), puede llamar

 SystemSoundID.playFileNamed("sound", withExtenstion: "mp3") 

para jugar “sound.mp3”

Esto crea un SystemSoundID desde un archivo llamado Cha-Ching.aiff .

 import AudioToolbox let chaChingSound: SystemSoundID = createChaChingSound() class CashRegisterViewController: UIViewController { override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) AudioServicesPlaySystemSound(chaChingSound) } } func createChaChingSound() -> SystemSoundID { var soundID: SystemSoundID = 0 let soundURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), "Cha-Ching", "aiff", nil) AudioServicesCreateSystemSoundID(soundURL, &soundID) CFRelease(soundURL) return soundID } 

Con una clase y AudioToolbox:

 import AudioToolbox class Sound { var soundEffect: SystemSoundID = 0 init(name: String, type: String) { let path = NSBundle.mainBundle().pathForResource(name, ofType: type)! let pathURL = NSURL(fileURLWithPath: path) AudioServicesCreateSystemSoundID(pathURL as CFURLRef, &soundEffect) } func play() { AudioServicesPlaySystemSound(soundEffect) } } 

Uso:

 testSound = Sound(name: "test", type: "caf") testSound.play() 
 import AVFoundation var audioPlayer = AVAudioPlayer() class GameScene: SKScene { override func didMoveToView(view: SKView) { let soundURL = NSBundle.mainBundle().URLForResource("04", withExtension: "mp3") audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: nil) audioPlayer.play() } } 

Este código funciona para mí. Utilice Try and Catch para AVAudioPlayer

 import UIKit import AVFoundation class ViewController: UIViewController { //Make sure that sound file is present in your Project. var CatSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Meow-sounds.mp3", ofType: "mp3")!) var audioPlayer = AVAudioPlayer() override func viewDidLoad() { super.viewDidLoad() do { audioPlayer = try AVAudioPlayer(contentsOfURL: CatSound) audioPlayer.prepareToPlay() } catch { print("Problem in getting File") } // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func button1Action(sender: AnyObject) { audioPlayer.play() } } 
 var mySound = NSSound(named:"Morse.aiff") mySound.play() 

“Morse.aiff” es un sonido de sistema de OSX, pero si solo hace clic en “named” dentro de XCode, podrá ver (en el panel QuickHelp) donde esta función está buscando los sonidos. Puede estar en su carpeta “Archivos de apoyo”

De acuerdo con el nuevo Swift 2.0 deberíamos usar do try catch. El código se vería así:

 var badumSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("BadumTss", ofType: "mp3")) var audioPlayer = AVAudioPlayer() do { player = try AVAudioPlayer(contentsOfURL: badumSound) } catch { print("No sound found by URL:\(badumSound)") } player.prepareToPlay() 

esto está trabajando con Swift 4:

 if let soundURL = Bundle.main.url(forResource: "note3", withExtension: "wav") { var mySound: SystemSoundID = 0 AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound) // Play AudioServicesPlaySystemSound(mySound); } 

Veamos un enfoque más actualizado a esta pregunta:

 Import AudioToolbox func noteSelector(noteNumber: String) { if let soundURL = Bundle.main.url(forResource: noteNumber, withExtension: "wav") { var mySound: SystemSoundID = 0 AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound) AudioServicesPlaySystemSound(mySound) } 

La solución de Matt Gibson funcionó para mí, aquí está la versión rápida 3.

 if let soundURL = Bundle.main.url(forResource: "ringSound", withExtension: "aiff") { var mySound: SystemSoundID = 0 AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound) AudioServicesPlaySystemSound(mySound); } 

Swift 4

 import UIKit import AudioToolbox class ViewController: UIViewController{ var sounds : [SystemSoundID] = [1, 2, 3, 4, 5, 6, 7] override func viewDidLoad() { super.viewDidLoad() for index in 0...sounds.count-1 { let fileName : String = "note\(sounds[index])" if let soundURL = Bundle.main.url(forResource: fileName, withExtension: "wav") { AudioServicesCreateSystemSoundID(soundURL as CFURL, &sounds[index]) } } } @IBAction func notePressed(_ sender: UIButton) { switch sender.tag { case 1: AudioServicesPlaySystemSound(sounds[0]) case 2: AudioServicesPlaySystemSound(sounds[1]) case 3: AudioServicesPlaySystemSound(sounds[2]) case 4: AudioServicesPlaySystemSound(sounds[3]) case 5: AudioServicesPlaySystemSound(sounds[4]) case 6: AudioServicesPlaySystemSound(sounds[5]) default: AudioServicesPlaySystemSound(sounds[6]) } } } 

o

 import UIKit import AVFoundation class ViewController: UIViewController, AVAudioPlayerDelegate{ var audioPlayer : AVAudioPlayer! override func viewDidLoad() { super.viewDidLoad() } @IBAction func notePressed(_ sender: UIButton) { let soundURL = Bundle.main.url(forResource: "note\(sender.tag)", withExtension: "wav") do { audioPlayer = try AVAudioPlayer(contentsOf: soundURL!) } catch { print(error) } audioPlayer.play() } } 

funciona en Xcode 9.2

 if let soundURL = Bundle.main.url(forResource: "note1", withExtension: "wav") { var mySound: SystemSoundID = 0 AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound) // Play AudioServicesPlaySystemSound(mySound); } 
 //Swift 4 import UIKit import AVFoundation class ViewController: UIViewController { var player : AVAudioPlayer? override func viewDidLoad() { super.viewDidLoad() } @IBAction func notePressed(_ sender: UIButton) { let path = Bundle.main.path(forResource: "note1", ofType: "wav")! let url = URL(fileURLWithPath: path) do { player = try AVAudioPlayer(contentsOf: url) player?.play() } catch { // error message } } } 

Ejemplo de código Swift :

 import UIKit import AudioToolbox class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } @IBAction func notePressed(_ sender: UIButton) { // Load "mysoundname.wav" if let soundURL = Bundle.main.url(forResource: "note1", withExtension: "wav") { var mySound: SystemSoundID = 0 AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound) // Play AudioServicesPlaySystemSound(mySound); } } 

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") 

Este código funciona para mí:

 class ViewController: UIViewController { var audioFilePathURL : NSURL! var soundSystemServicesId : SystemSoundID = 0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. audioFilePathURL = NSBundle.mainBundle().URLForResource("MetalBell", withExtension: "wav") AudioServicesCreateSystemSoundID( audioFilePathURL, &soundSystemServicesId) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func PlayAlertSound(sender: UIButton) { AudioServicesPlayAlertSound(soundSystemServicesId) } } 

Para Swift 3 :

 extension SystemSoundID { static func playFileNamed(_ fileName: String, withExtenstion fileExtension: String) { var sound: SystemSoundID = 0 if let soundURL = Bundle.main.url(forResource: fileName, withExtension: fileExtension) { AudioServicesCreateSystemSoundID(soundURL as CFURL, &sound) AudioServicesPlaySystemSound(sound) } } }