如何使用Swift播放声音?
我想使用Swift播放声音。
I would like to play a sound using Swift.
我的代码在Swift 1.0中运行但现在它在Swift 2或更新版本中不再起作用。
My code worked in Swift 1.0 but now it doesn't work anymore in Swift 2 or newer.
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 。
它提供了使用视听媒体的所有必需品。
更新:根据评论中的一些人的建议,与 Swift 2 , Swift 3 和 Swift 4 兼容。
Update: Compatible with Swift 2, Swift 3 and Swift 4 as suggested by some of you in the comments.
Swift 2.3
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
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(兼容iOS 11)
Swift 4 (iOS 11 compatible)
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)
}
}
确保更改tun的名称e以及扩展程序。
该文件需要正确导入(项目构建阶段
>复制捆绑资源
)。您可能希望将它放在assets.xcassets
中,以便更方便
。
Make sure to change the name of your tune as well as the extension. The file needs to be properly imported (
Project Build Phases
>Copy Bundle Resources
). You might want to place it inassets.xcassets
for greater convenience.
对于简短的声音文件,您可能希望使用非压缩音频格式,例如 .wav
,因为它们具有最佳质量和低cpu影响。对于短声音文件,较高的磁盘空间消耗不应该是一个大问题。文件越长,您可能想要使用压缩格式,例如 .mp3
等。检查 CoreAudio .com / library / content / documentation / MusicAudio / Conceptual / CoreAudioOverview / SupportedAudioFormatsMacOSX / SupportedAudioFormatsMacOSX.htmlrel =noreferrer>兼容音频格式 CoreAudio
。
For short sound files you might want to go for non-compressed audio formats such as .wav
since they have the best quality and a low cpu impact. The higher disk-space consumption should not be a big deal for short sound files. The longer the files are, you might want to go for a compressed format such as .mp3
etc. pp. Check the compatible audio formats of CoreAudio
.
有趣的事实:有一些简洁的小库可以播放声音更容易。 :)
例如: SwiftySound
Fun-fact: There are neat little libraries which make playing sounds even easier. :)
For example: SwiftySound