最好使用AVFoundation。
它提供了所有与视听媒体工作的必要条件。
更新:兼容Swift 2, Swift 3和Swift 4,正如你们中的一些人在评论中建议的那样。
斯威夫特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)
}
}
斯威夫特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 13)
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)
}
}
请确保更改您的曲调的名称以及扩展名。
文件需要正确导入(Project Build Phases > Copy Bundle Resources)。你可以把它放在资产里。xcassets为
更大的便利。
对于短音频文件,你可能想要使用非压缩音频格式,如。wav,因为它们具有最好的质量和低cpu消耗。对于较短的声音文件来说,较高的磁盘空间消耗应该不是什么大问题。文件越长,你可能想要使用压缩格式,如。mp3等。检查CoreAudio的兼容音频格式。
有趣的事实:有一些整洁的小库可以让播放声音更容易。:)
例如:SwiftySound