我创建了一个Sound类,并在我的场景文件中放置了一个方法,以便在视图开始时调用音频。
我还在构建阶段链接了AudioToolbox.framework。
所有在我的模拟器上运行正常,但声音在实际设备上无法播放。
static let sharedInstance = Sound()
private let music = "filename.mp3"
private var player = AVAudioPlayer()
private var initialized = false
func playMusic() {
let url = URL(fileURLWithPath: Bundle.main.path(forResource: "filename", ofType: nil)!)
do {
player = try AVAudioPlayer(contentsOf: url)
} catch let error as NSError {
NSLog("Error playing music: %@", error)
}
player.numberOfLoops = -1
player.prepareToPlay()
player.play()
initialized = true
}