Swift:锁定装置时继续播放声音 [英] Swift: Keep playing sounds when the device is locked

查看:99
本文介绍了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:锁定装置时继续播放声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆