我正在使用钢琴键盘开发应用程序。我希望按下按键后的声音,当“响铃/静音”开关打开时。然后它应该停止其他应用程序的背景音乐。如果“铃声/静音”开关处于静音状态,则它不应该执行任何操作,并让其他应用程序播放背景音乐(如Spotify)。
我尝试过(使用Spotify作为背景音乐):
选项1 [AVAudioSessionCategoryAmbient]:
选项2 [AVAudioSessionCategorySoloAmbient]:
我认为选项2是我能得到的最接近的选择。当“响铃/静音”开关处于静音状态时,iPhone不应该停止背景音乐,我会很开心。
选项3 [AVAudioSessionCategoryPlayback]:
我的代码:
let NoteSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: currentNote.sound, ofType: "m4a")!)
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
try AVAudioSession.sharedInstance().setActive(true)
audioPlayer = try AVAudioPlayer(contentsOf: NoteSound as URL)
audioPlayer.prepareToPlay()
audioPlayer.play()
} catch {
print("Problem in getting File")
}
在代码示例中,我只更改了.setCategory()
。
没有原生API来检查手机是否处于静音状态,并且不建议您根据此类用户选择使用应用程序的功能(在低电量模式下,是否充电,......)。
有一个黑客可以检查设备是否静音:播放0.5s最短持续时间的短音,并检测播放所需的时间。有关此变通方法的更多详细信息,请查看here。