gpt4 book ai didi

iOS, swift : play background music and sound effects without delay

转载 作者:行者123 更新时间:2023-11-29 02:30:10 25 4
gpt4 key购买 nike

我正在尝试在不使用 SpriteKit 的情况下在 iOS 中创建游戏。我一直致力于让音效及时播放。我一直在使用我在网上找到的以下代码,并且背景音乐播放得很好。但是,当我使用“playSoundEffect”方法第一次播放正常,但随后开始落后并变得不同步。我猜发生这种情况是因为它每次都会初始化一个 AVAudioPlayer 。有人知道如何在播放背景音乐的同​​时及时播放音效吗?谢谢!

import AVFoundation

public class SKTAudio: NSObject, AVAudioPlayerDelegate {
public var backgroundMusicPlayer: AVAudioPlayer?
public var soundEffectPlayer: AVAudioPlayer?

private var mainLoopFileName:String! {

let randomSong = Int(arc4random_uniform(3))

switch randomSong {
//case 0: return "Test.mp3"
//case 1: return "Test2.mp3"
case 0: return "SneakySnitch.mp3"
case 1: return "FasterDoesIt.mp3"
case 2: return "MonkeysSpinningMonkeys.mp3"
default:
break
}

return "SneakySnitch.mp3"
}

public class func sharedInstance() -> SKTAudio {
return SKTAudioInstance
}

public func playBackgroundMusic() {
let filename = mainLoopFileName
let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil)
if (url == nil) {
println("Could not find file: \(filename)")
return
}

var error: NSError? = nil
backgroundMusicPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
if let player = backgroundMusicPlayer {
player.numberOfLoops = 0
player.delegate = self
player.prepareToPlay()
player.play()
} else {
println("Could not create audio player: \(error!)")
}
}

public func pauseBackgroundMusic() {
if let player = backgroundMusicPlayer {
if player.playing {
player.pause()
}
}
}

public func resumeBackgroundMusic() {
if let player = backgroundMusicPlayer {
if !player.playing {
player.play()
}
}
}

public func playSoundEffect(filename: String) {
let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil)
if (url == nil) {
println("Could not find file: \(filename)")
return
}

var error: NSError? = nil
soundEffectPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
if let player = soundEffectPlayer {
player.numberOfLoops = 0
player.prepareToPlay()
player.play()
} else {
println("Could not create audio player: \(error!)")
}
}

// MARK: AVAudioPlayerDelegate
public func audioPlayerDidFinishPlaying(player: AVAudioPlayer!, successfully flag: Bool) {
println("finished playing \(flag)")

delay(5.0, {
self.playBackgroundMusic()
})
}

public func audioPlayerDecodeErrorDidOccur(player: AVAudioPlayer!, error: NSError!) {
println("\(error.localizedDescription)")
}

}

最佳答案

您可以使用 AVPlayer 来播放您的声音文件。保留一个播放器,但当您需要播放新声音时,将其 AVPlayerItem 更改为一个新项目。这可能比每次都重新创建播放器更快。

虽然 AVAudioPlayer/AVPlayer 是最简单的选项,但它不会在播放音频文件时为您提供最短的延迟或完美的同步。您应该查看 Core Audio 中的音频队列或音频单元以获得更准确的声音播放。

关于iOS, swift : play background music and sound effects without delay,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26998764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com