本文介绍了Swift:锁定装置时继续播放声音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用以下代码从Internet上的URL播放声音:
I'm using the following code to play a sound off a URL from the internet:
var audioPlayer = AVPlayer()...
let audioSession = AVAudioSession.sharedInstance() audioSession.setCategory(AVAudioSessionCategoryAmbient, error: nil) let url = trackFileName let playerItem = AVPlayerItem( URL:NSURL( string:url ) ) audioPlayer = AVPlayer(playerItem:playerItem) audioPlayer.rate = 1.0; player.play()我正在尝试确保它在后台继续播放,这就是为什么我使用"AVAudioSession.sharedInstance()"的原因.当我通过锁定屏幕在模拟器中进行尝试时,它会像预期的那样继续播放.但是,如果我在设备上播放,屏幕自动显示或我自己锁定时,声音就会关闭.
I'm trying to make sure it keeps playing in the background which is the reason why I'm using "AVAudioSession.sharedInstance()". When I try it out in the simulator by locking the screen, it keeps playing like it's supposed to. But if I play it in a device, the sounds shuts off as soon as the screen looks itself automatically or I lock it myself.
我的代码中缺少什么?
推荐答案swift 2+解决方案:
swift 2+ solution:
do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) try AVAudioSession.sharedInstance().setActive(true) } catch _ { return print("error") }
更多推荐
Swift:锁定装置时继续播放声音
发布评论