我怎样才能避免中断了正在播放时,我的应用程序启动声音? [英] How can I avoid interrupting audio that is already playing when my app launches?

查看:243
本文介绍了我怎样才能避免中断了正在播放时,我的应用程序启动声音?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有需求,以便在设备锁定或我的应用程序在后台播放的声音使用 AVAudioSessionCategoryPlayback 的应用程序。 (这是一个报警的功能。)所以我还需要设置在我UIBackgroundModes列表中的声音键。

我已经把下面的code在我的的application:didFinishLaunchingWithOptions:方法:


  [AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback
                                 withOptions:AVAudioSessionCategoryOptionMixWithOthers
                                       错误:无];


不过,我不想打断了正在播放设备上的任何音乐。当我的应用程序启动时,它会导致Spotify的(例如)停止播放音乐。我可以切换到Spotify和preSS发挥,而当我切换回我的应用程序,它会继续播放。

但是,这是非常恼人的用户 - 警都不是我的应用程序做的唯一的事情,有很多理由为他们启动它不涉及设置报警。我不认为用户会永远想我的应用程序停止设备上的任何其他音频播放。

理想我的从不的中断已经扮演音频。我还可以与停机时报警设置(在这一点上我要激活我的音频会议,以确保我能够发挥它)音频生活,但好像也没有办法,我要避免音频停在应用程序启动。

有没有一些方法来禁用音频会话启动我的应用程序,或与该选项已经应用启动?


解决方案

原来,我打电话<$ C C>。prepareForPlayback()在一个AVAudioPlayer在的init()方法这是获取调用之前我 didFinishLaunchingWithOptions长:解雇

I have an app that needs to use AVAudioSessionCategoryPlayback in order to play sound while the device is locked or my app is in the background. (It's an alarm feature.) So I also need to set the "audio" key in my UIBackgroundModes list.

I have put the following code in my application:didFinishLaunchingWithOptions: method:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback
                                 withOptions:AVAudioSessionCategoryOptionMixWithOthers
                                       error:nil];

However, I don't want to interrupt any music that is already playing on the device. When my app is launched, it causes Spotify (for example) to stop playing music. I can switch to Spotify and press play, and when I switch back to my app, it continues playing.

But this is very annoying to the user - alarms are not the only thing my app does, and there are many reasons for them to launch it that don't involve setting alarms. I don't think the user would ever want my app to stop any other audio playing on the device.

Ideally I'd never interrupt already-playing audio. I could also live with stopping audio when an alarm is set (at which point I have to activate my audio session to ensure that I'm able to play it) but it seems like there is no way for me to avoid the audio stop at app launch.

Is there some way to start my app with the audio session disabled, or to start it with this option already applied?

解决方案

It turns out that I was calling .prepareForPlayback() on an AVAudioPlayer in an init() method which was getting called long before my didFinishLaunchingWithOptions: fired.

这篇关于我怎样才能避免中断了正在播放时,我的应用程序启动声音?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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