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

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

问题描述

我想在前台、后台播放音频文件,它应该与静音开关配合使用,即如果静音开关打开,那么它不应该播放,如果静音开关关闭应该播放音频.

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 呼叫应用程序.当用户接到电话时,应用程序应播放声音/铃声.如果应用程序在后台/前台,它应该播放,如果硬件静音开关打开/关闭,它应该静音/取消静音.

**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天全站免登陆