Swift:音频在 0.1 秒内开始和停止
Swift: Audio start and stop in .1 second
我在网上关注了每个 post,但 none 解决了这个问题。
声音在 0.1 秒后立即开始和停止。我能很快听到声音。
这是我重要的代码:
...
let path = NSBundle.mainBundle().pathForResource("bgMusic", ofType: "mp3")
let bgMusicURL = NSURL.fileURLWithPath(path!)
var backgroundMusicPlayer:AVAudioPlayer!
do{
try AVAudioSession.sharedInstance().setActive(true)
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try backgroundMusicPlayer = AVAudioPlayer(contentsOfURL: bgMusicURL)
backgroundMusicPlayer!.prepareToPlay()
backgroundMusicPlayer!.play()
}catch {
print ("ERROR")
}
...
当包含您的代码片段的函数结束时,垃圾收集器将释放您的 backgroundMusicPlayer
。尝试将 backgroundMusicPlayer
设为全局变量,或者使用某种静态变量来保存它。
我在网上关注了每个 post,但 none 解决了这个问题。 声音在 0.1 秒后立即开始和停止。我能很快听到声音。
这是我重要的代码: ...
let path = NSBundle.mainBundle().pathForResource("bgMusic", ofType: "mp3")
let bgMusicURL = NSURL.fileURLWithPath(path!)
var backgroundMusicPlayer:AVAudioPlayer!
do{
try AVAudioSession.sharedInstance().setActive(true)
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try backgroundMusicPlayer = AVAudioPlayer(contentsOfURL: bgMusicURL)
backgroundMusicPlayer!.prepareToPlay()
backgroundMusicPlayer!.play()
}catch {
print ("ERROR")
}
...
当包含您的代码片段的函数结束时,垃圾收集器将释放您的 backgroundMusicPlayer
。尝试将 backgroundMusicPlayer
设为全局变量,或者使用某种静态变量来保存它。