我想用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。它提供了使用视听媒体的所有必要条件。
更新: 某些评论中建议与 Swift 2 , Swift 3 和 Swift 4 兼容。
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) } }
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) } }
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更大的便利中。
Project Build Phases
Copy Bundle Resources
assets.xcassets
对于短声音文件,您可能想要使用非压缩音频格式,例如,.wav因为它们具有最佳的质量和较低的cpu影响。对于短声音文件而言,较高的磁盘空间消耗不应该是大问题。较长的文件,你可能会想要去的压缩格式,如.mp3等页。检查兼容的音频格式的CoreAudio。
.wav
.mp3
CoreAudio
趣味: 整洁的小资料库使播放声音更加轻松。:) 例如:SwiftySound