音频播放器在后台播放,应该基于硬件静音开关才能正常工作 [英] Audio Player play in background and should work based off of hardware mute switch

查看:163
本文介绍了音频播放器在后台播放,应该基于硬件静音开关才能正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在前景,背景中播放音频文件,并且该文件应与静音开关一起使用,即,如果静音开关打开,则不应播放,如果静音开关关闭,则应该播放音频.

I want to play audio file in the foreground, background and it should work with mute switch i.e. if mute switch is on, then it should not play, if mute switch is off should play audio.

**我正在开发SIP呼叫应用程序.用户接听电话时,应用程序应播放声音/铃声.如果应用程序在背景/前景中,则应播放;如果硬件静音开关为ON/OFF,则应将其静音/取消静音.

**I'm developing an SIP call application. App should play sound/ringtone when user receives a call. It should play if app is in background/foreground, it should mute/unmute if hardware mute switch is ON/OFF.

为此,我将AVPlyaer与以下代码配合使用.

For this I used AVPlyaer with below code.

AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:&error];
[session setActive:YES error:nil];

NSURL * audioFileUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"test1" ofType:@"mp3"]];
AVPlayer *player = [[AVPlayer alloc] initWithURL: audioFileUrl];
[player play];

此外,我还在info.plist的后台模式中添加了应用程序使用AirPlay播放音频或流音频/视频"

And also I added "App plays audio or streams audio/video using AirPlay" to background modes in info.plist

在两种模式下都可以播放,但是当硬件静音开关打开时不会静音. 如果使用AVAudioSessionCategoryAmbient,则不能在后台模式下播放. 我使用了AVAudioPlayer,但是在硬件开关打开时找不到静音

This is playing in both modes but not mute when hardware mute switch is ON. If I use AVAudioSessionCategoryAmbient not playing on the background mode. I used AVAudioPlayer but not able to find mute when hardware switch is ON

推荐答案

很高兴地说,我发现skype如何实现此功能.

Am happy to say, I found how skype is achieving this feature.

在前台,我们可以将AVAudioSession与任何一种类别一起使用来播放铃声.

In foreground we can use AVAudioSession with any one category to play ringtone.

AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory: AVAudioSessionCategorySoloAmbient error:&error];
[session setActive:YES error:nil];

NSURL * audioFileUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"test1" ofType:@"mp3"]];
AVPlayer *player = [[AVPlayer alloc] initWithURL: audioFileUrl];
[player play];

在后台,我们必须使用具有自定义声音的本地通知.这将与硬件静音开关一起使用.但是这里的声音文件长度不应超过30秒.

In background we have to use local notification with custom sound. This will work with hardware mute switch. But here sound file length should not exceed 30 seconds.

    UILocalNotification* notification = [[UILocalNotification alloc] init];
    [notification @"Title"];
    [notification setAlertBody:@"Body"];
    [notification setAlertAction:noteAction];
    [notification setSoundName:@"ringtone.mp3"];
    [[UIApplication sharedApplication] presentLocalNotificationNow:notification];

希望这会很有用:).

这篇关于音频播放器在后台播放,应该基于硬件静音开关才能正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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