iOS:如何检测任何后台音乐应用程序是否正在播放音乐?

19

目前我的游戏可以正确地在系统内置iPod应用程序播放音乐时停止背景音乐,但它无法检测到像Pandora这样的应用在播放音乐。

目前,在我的applicationDidBecomeActive方法中,我检查[[MPMusicPlayerController iPodMusicPlayer] playbackState]来确定是否正在播放音乐。如何等效地检查类似Pandora的应用在后台播放音频?

4个回答

27

AudioSessionGetProperty(如jake_hetfield的回答所述)已于iOS 7中被弃用。

相反,尝试使用这个使用isOtherAudioPlaying的一行代码:

BOOL isOtherAudioPlaying = [[AVAudioSession sharedInstance] isOtherAudioPlaying];

适用于iOS 6及以上版本。


1
Swift 2.3 版本:var otherAudioPlaying = AVAudioSession.sharedInstance().otherAudioPlaying - Callam
3
Swift 3: var otherAudioPlaying = AVAudioSession.sharedInstance().isOtherAudioPlaying - Emil Korngold

14

请查看此问题

似乎您可以通过检查kAudioSessionProperty_OtherAudioIsPlaying属性来查看是否正在播放其他音频,方法如下:

UInt32 propertySize, audioIsAlreadyPlaying=0;
propertySize = sizeof(UInt32);
AudioSessionGetProperty(kAudioSessionProperty_OtherAudioIsPlaying, &propertySize, &audioIsAlreadyPlaying);

另外一个补充是询问用户是否想要游戏音乐或者已经播放的声音/音乐。


谢谢!我进行了大量搜索,但不知何故从未找到这个问题。我不打算询问用户,我认为只要推断出用户已经在播放自己的音乐并想继续聆听即可。 - Tim R.
我现在从kAudioSessionProperty_OtherAudioIsPlaying 得到了一个虚假的正面结果。其他音频绝对没有播放(我停止了我的 iPhone 5 iOS 6.x 上的 iPod)。这种情况有时会发生。就像某些东西卡在那里一样,使 kAudioSessionProperty_OtherAudioIsPlaying 总是返回 YES/1/true/positive。通常只有重启设备后才能解决。 - Jonny
1
请注意,这可能不是误报。有些应用程序会播放“静音音频”(即没有声音的短音频文件)以绕过15分钟的空闲计时器。可能是某个应用程序正在执行此操作,从而触发了检查的真实返回值。只是一个想法。 - stuckj

4

iOS 8版本开始应使用secondaryAudioShouldBeSilencedHint属性:

/* Will be true when another application with a non-mixable audio session is playing audio.  Applications may use
this property as a hint to silence audio that is secondary to the functionality of the application. For example, a game app
using AVAudioSessionCategoryAmbient may use this property to decide to mute its soundtrack while leaving its sound effects unmuted.
Note: This property is closely related to AVAudioSessionSilenceSecondaryAudioHintNotification.
*/
@property(readonly) BOOL secondaryAudioShouldBeSilencedHint  NS_AVAILABLE_IOS(8_0);

-1
你可能想要做类似这样的事情......
  1. 创建一个处理音频设置的类,比如说... "AudioManager"

  2. 轮询布尔值"isOtherAudioPlaying"......也许将其分配给你自己的布尔值。

import Foundation
import AVFoundation

class AudioManager {
    static let successBingSoundID: SystemSoundID = <Your System Sound ID in Int>
    static func playSystemSoundIfBackgroundSoundIsOff() {
        guard !AVAudioSession.sharedInstance().isOtherAudioPlaying else {return}
        AudioServicesPlaySystemSoundWithCompletion(successBingSoundID, nil)
    }
}

用法:

AudioManager.playSystemSoundIfBackgroundSoundIsOff()

这个回答并没有提供其他回答中所没有的内容,除了增加一个多余的步骤来添加音频管理器类。你提供的示例甚至不能在没有构建另一个音频管理器的情况下多次轮询该值。 - Tim R.
@TimR。我同意你的观点。但是有时候为了分离逻辑而创建一个新类是很有用的。此外,@hoboBob实际上提供了.isOtherAudioPlaying的Swift版本,它提供了一些有用的信息。我修改了原始代码,以便人们可以轻松地使用它们。 - Hitit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接