Swift:锁定装置时继续播放声音

编程入门 行业动态 更新时间:2024-10-25 13:18:29
本文介绍了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:锁定装置时继续播放声音

本文发布于:2023-07-11 12:07:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1093999.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:装置   声音   Swift

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!