我想用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
}
}
发布于 2015-08-16 14:41:08
最理想的情况是您可能希望使用 AVFoundation。它提供了使用视听媒体的所有基本要素。
更新:兼容Swift 2、Swift 3和Swift 4,这是你们中的一些人在评论中提出的。
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
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)
}
}
确保更改您的调名以及http://wikipedia.org/wiki/Audio_file_format。文件需要正确导入(__
Project Build Phases
>Copy Bundle Resources
__)。为了更方便起见,您可能需要将其放置在assets.xcassets
中。
对于短声音文件,您可能需要使用非压缩音频格式,如.wav
,因为它们具有最好的质量和较低的cpu影响。较高的磁盘空间消耗不应该是短声音文件的大问题。文件越长,您可能需要使用压缩格式,如.mp3
等。检查https://developer.apple.com/library/content/documentation/MusicAudio/Conceptual/CoreAudioOverview/SupportedAudioFormatsMacOSX/SupportedAudioFormatsMacOSX.html of CoreAudio
__。
有趣-事实:有一些整洁的小库,使播放听起来更容易。:)
例如:SwiftySound
发布于 2016-10-08 15:21:21
对于Swift 3:
import AVFoundation
/// **must** define instance variable outside, because .play() will deallocate AVAudioPlayer
/// immediately and you won't hear a thing
var player: AVAudioPlayer?
func playSound() {
guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else {
print("url not found")
return
}
do {
/// this codes for making this app ready to takeover the device audio
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
/// change fileTypeHint according to the type of your audio file (you can omit this)
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3)
// no need for prepareToPlay because prepareToPlay is happen automatically when calling play()
player!.play()
} catch let error as NSError {
print("error: \(error.localizedDescription)")
}
}
本地资产的最佳实践是将其放入assets.xcassets
中,然后按如下方式加载文件:
func playSound() {
guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else {
print("url not found")
return
}
do {
/// this codes for making this app ready to takeover the device audio
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
/// change fileTypeHint according to the type of your audio file (you can omit this)
/// for iOS 11 onward, use :
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
/// else :
/// player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3)
// no need for prepareToPlay because prepareToPlay is happen automatically when calling play()
player!.play()
} catch let error as NSError {
print("error: \(error.localizedDescription)")
}
}
发布于 2021-06-28 17:48:44
迅捷版: 5.4及以上
import AVFoundation
var player: AVAudioPlayer?
func playSound() {
guard let path = Bundle.main.path(forResource: "beep", ofType:"mp3") else {
return }
let url = URL(fileURLWithPath: path)
do {
player = try AVAudioPlayer(contentsOf: url)
player?.play()
} catch let error {
print(error.localizedDescription)
}
}
https://stackoverflow.com/questions/32036146
复制相似问题