如何使用Swift播放声音?

我想用Swift播放声音。

我的代码在Swift 1.0中工作,但现在在Swift 2或更新版本中不再有效。

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

最好你可能想使用AVFoundation 。 它提供了与视听媒体合作的所有必要条件。

更新:与你们中的一些人在评论中build议的Swift 2Swift 3Swift 4兼容。


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) player = try AVAudioPlayer(contentsOf: url) guard let player = player else { return } player.play() } catch let error { print(error.localizedDescription) } } 

Swift 4(iOS 11兼容)

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

确保改变曲调的名称以及扩展名 。 该文件需要正确导入( Project Build Phases > Copy Bundle Resources )。 您可能希望将其放在assets.xcassets以获得更大的方便。

对于简短的声音文件,您可能想要使用非压缩audio格式,如.wav因为它们具有最好的质量和较低的cpu影响。 较高的磁盘空间消耗对于短小的声音文件应该不是什么大问题。 文件时间越长,您可能需要使用.mp3等压缩格式。请检查CoreAudio的兼容audio格式 。


有趣的事实:有一些整齐的小库可以让播放声音变得更加简单。 🙂
例如: SwiftySound

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

本地资产的最佳做法是将其放置在assets.xcassets并像下面这样加载文件:

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

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 }