快速创build和播放声音

所以我想要做的就是快速创build和播放声音,当我按下button时,我知道如何在Objective-C中做到这一点,但有谁知道如何在Swift中?

Objective-C就是这样:

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

然后玩它,我会做的:

 AudioServicesPlaySystemSound(Explosion); 

有谁知道我能做到这一点?

这里有一些我已经添加到FlappySwift工作的代码:

 import SpriteKit import AVFoundation class GameScene: SKScene { // Grab the path, make sure to add it to your project! var coinSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("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() } } 

这与其他一些答案类似,但也许多一点“Swifty”:

 // Load "mysoundname.wav" if let soundURL = NSBundle.mainBundle().URLForResource("mysoundname", withExtension: "wav") { var mySound: SystemSoundID = 0 AudioServicesCreateSystemSoundID(soundURL, &mySound) // Play AudioServicesPlaySystemSound(mySound); } 

请注意,这是一个在问题中重现代码效果的简单例子。 您需要确保import AudioToolbox ,此类代码的一般模式是在您的应用程序启动时加载声音,将它们保存在某处的SystemSoundID实例variables中,在整个应用程序中使用它们,然后在调用AudioServicesDisposeSystemSoundID时调用AudioServicesDisposeSystemSoundID你完成了他们。

这将从一个名为Cha-Ching.aiff的文件创build一个SystemSoundID

 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 } 

方便的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) } } } 

然后,从您的应用程序的任何地方(记得import AudioToolbox ),你可以打电话

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

播放“sound.mp3”

随着类和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) } } 

用法:

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

这段代码适用于我。 使用Try and Catch for 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”是OSX的系统声音,但是如果您只需在XCode中单击“named”,就可以查看(在QuickHelp窗格中)此functionsearch声音的位置。 它可以在你的“支持文件”文件夹中

根据新的Swift 2.0,我们应该使用try try。 代码看起来像这样:

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

使用此function在Swift中发声(您可以在想要发声的位置使用此function。)

首先添加SpriteKit和AVFoundation框架。

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

这段代码适用于我:

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

对于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) } } } 

马特吉布森的解决scheme为我工作,这里是迅速的3版本。

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

斯威夫特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]) } } } 

要么

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