如何使用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
}
}
回答:
某些评论中建议与 , 和 兼容。
回答:
import AVFoundationvar 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 AVFoundationvar 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 AVFoundationvar 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
以上是 如何使用Swift播放声音? 的全部内容, 来源链接: utcz.com/qa/422971.html