最可取的是,您可能想使用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
)。您可能希望将其放置在assets.xcassets
更大的便利中。
对于短声音文件,您可能需要使用非压缩音频格式,例如,.wav
因为它们具有最佳的质量和较低的cpu影响。对于短声音文件而言,较高的磁盘空间消耗不应该是大问题。较长的文件,你可能会想要去的压缩格式,如.mp3
等页。检查兼容的音频格式的CoreAudio
。
趣味:整洁的小资料库使播放声音更加轻松。:)
例如:SwiftySound