Playing sound when device is in silent mode - ios

I am new to coding applications, and I have created a simple app that plays a sound. I have tested it and it works just fine. However, I want to play the sound on silent mode.
Here is the code:
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
-(IBAction)Button1Sound:(id)sender{
AudioServicesPlaySystemSound(Button1);
}
- (void)viewDidLoad {
NSURL *Button1Sound = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"nobody" ofType:#"m4a"]];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)Button1Sound, & Button1);
[super viewDidLoad];
}
#end
I have looked at other questions online, and they said to add this line of code:
[[AVAudioSession sharedInstance]
setCategory: AVAudioSessionCategoryPlayback
error: nil];
I am not sure where to put it or if I am using the right syntax. I am using an audiotoolbox framework as well.

When in silent mode, unless the user explicitly initiates sound playback, such as media playback, it is in violation of the Human Interface Guidelines (HIG) and is grounds for the app being rejected.
Per the HIG:
Silence. People switch their device to silent to avoid being interrupted by unexpected sounds, such as ringtones and incoming message sounds. They also want nonessential sounds disabled, including keyboard sounds, sound effects, game soundtracks, and other audible feedback. When the device is set to silent, only explicitly initiated sounds should occur, such as audio during media playback, alarms, and audio/video messaging.
If you feel your need is not in violation, see this post for a solution.

Related

Music App (playing in background) breaks while recording video using AVCaptureSession

I am working on snapchat app like functionality. In my application, music app is running in the background and my app is in foreground state. I have to capture video simultaneously with music app running in the background.
Problem :- when my app comes in foreground state, the music app audio break for a second and then continue. Same problem arises when user tap HOME button, app went to background state and the music app audio break for a second.
I have downloaded the apple sample code for recording https://developer.apple.com/library/ios/samplecode/AVCam/Introduction/Intro.html#//apple_ref/doc/uid/DTS40010112
After downloading following changes have been done in the AppDelegate
In AppDelegate.h
import AVFoundation
#property (nonatomic, retain) AVAudioSession *session1;
In AppDelegate.m
self.session1 = [AVAudioSession sharedInstance];
[self.session1 setCategory:AVAudioSessionCategoryAmbient
withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker | AVAudioSessionCategoryOptionMixWithOthers | AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers error:nil];
[self.session1 setActive:YES error:nil];
// Inform the device that we want to use the device orientation.
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
In AAPLCameraViewController.m
Two properties have been added
self.session.usesApplicationAudioSession=TRUE;
self.session.automaticallyConfiguresApplicationAudioSession=FALSE;
Another Way
I have tried using SCRecorder Library but same issue is coming with that library. Source code can be reached from Github
https://github.com/sumitsharma/SCRecorderDemo

Keeping the video player silent after the recording is completed

How to keep the video player silent after the video recorder has been initialized and the silent switched is turned on?
In the application I am working on I have a video player (will call it player) and a video recorder (will call it recorder). If the phone is in silent mode (the switch on the side of the device is turned on to disable the sound) the player is kept silent when entering the application which is an expected and desired result. But after the recorder has begun running the session this behavior is lost and the video will play out loud although the silent mode is enabled.
I know specifically where this happens is when startRunning is called on an AVCaptureSession.
I also know the reason is somewhere in [AVAudioSession sharedInstance] category or mode property which seem to be changed right after the session begins running.
So what I do at the moment is call
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategorySoloAmbient error:&error];
[[AVAudioSession sharedInstance] setMode:AVAudioSessionModeDefault error:&error];
after the recording is completed to reset the session. The issue is this works in most but not all cases, sometimes reports error, sometimes works with a delay, sometimes doesn't work at all.
The possible solutions I am looking for are (any would do):
Somehow prevent the recorder to enable sound playing
Have a clear way of resetting the category and mode after the recording has completed (no errors or misbehaving)
Have a clean solution to find the state of the silence button (seems the old functions are deprecated and I found nothing but hacks)
Any other ideas welcome
An important information is that I have both the player and a recorder initialized all the time for a quick usage. Also I can control the player to be mute.
What I use for player:
AVFoundation
AVPlayer
AVPlayerLayer
The source is an AVAsset representing a remote URL
The implementation is pretty standard.
What I use for the recorder:
AVFoundation
AVCaptureDeviceInput
AVCaptureMovieFileOutput
AVCaptureVideoPreviewLayer
Again all pretty standard.

MPMusicPlayerController Play music while app is in background

Hope this question doesn't get down voted - I haven't seen anything in the documentation.
I want to play music from the ipod library while the app is in the back ground.
I am creating the music player using the default mechanism.
-(void)viewWillAppear:(BOOL)animated
{
MPMusicPlayerController *myPlayer =
[MPMusicPlayerController applicationMusicPlayer];
// assign a playback queue containing all media items on the device
[myPlayer setQueueWithQuery: [MPMediaQuery songsQuery]];
// start playing from the beginning of the queue
[myPlayer play];
}
As soon as the app enters the background the music stops playing. I would like it to continue playing though.
I do not want to use the iPodMusicPlayer option
How can I do this?
You should set background audio mode in the project settings (Project settings > Capabilities > Background modes > Audio and AirPlay) like it's shown on the screenshot below:
Also you should set Audio Session Category in the appDelegate (in the didFinishLaunching method). Example is shown below:
NSError *setCategoryErr = nil;
NSError *activationErr = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&setCategoryErr];
[[AVAudioSession sharedInstance] setActive:YES error:&activationErr];
I have same issue. I searched even after added flag in plist. It will not work because :
The applicationMusicPlayer does not support background music. Use
MPMusicPlayerController's systemMusicPlayer instead. It shares the
state with the built-in System player and music will continue to play
when your app enters the background.
Other Solution is :
You can use AVAudioPlayer to play either streamed or local(bundle) audio. It even allows you to play multiple audio file at the same time having an AVAudioPlayer instance for each.
Note : iPodMusicPlayer is deprecated. so Instead of this use systemMusicPlayer.

IOS 5 No audio when playing a video with Silent mode on with a buzztouch app

I have done several apps with buzztouch for Iphone and Ipads, here is a free one as an example :
http://itunes.apple.com/us/app/lr-basics-free-edition/id497563707?mt=8
I do not know code very much, I have very little basics that is why I designed my app using Buzztouch, which by the way is amazing !
The only one problem that I have is that the default behavior when you play a video (which was most of my apps are doing, playing tutorials) and if the silent mode is on either on Ipad or Iphone, there is no audio, even thought the volume slider is active, given the impressions to users that there is a bug, and I got some bad reviews due to that, I have also people writing me about it. I Then tell them all they have to do is to turn off the silent mode and they the audio is back, works everytime, but in the meantime I get complaits !
So here is my questions, is there a simple way I can located in the Buzztouch generated code a property that can easely be changed so that when a video is played, audio stays, despiste the silent mode being active.
I actually checked 4 or 5 other Iphones similar applications including the default youtube apple app, the default is that the audio plays even if the silent mode is turn on, giving my customer the impression that my app is bugged.
I'm not a programmer so please but as simple as possible in your answer.
Tku so much for the help.
Serge
What you are describing is the default behavior in iOS - when the ring/silent switch is in silent mode all audio from your app will be suppressed.
I don't know about implementing this from BuzzTouch, but here is a native solution I used to get around this for one of my apps that plays video:
MPMoviePlayerViewController *mpvc = [[MPMoviePlayerViewController alloc] initWithContentURL:myVidURL];
... set up player ...
// prevent mute switch from switching off audio from movie player
NSError *_error = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &_error];
[self presentMoviePlayerViewControllerAnimated:mpvc];
You will also need to include the AVFoundation framework for this to work.
Here's the link where I first found this tip:
http://www.24100.net/2011/05/ignore-ringtone-mute-switch-during-mpmovieplayer-video-playback-ios/
Right from documentation - iOS has 6 audio session categories out of that 3 affects the behavior of Slient switch:
AVAudioSessionCategoryAmbient or the equivalent kAudioSessionCategory_AmbientSound— Using this category, your audio is silenced by the Ring/Silent switch and when the screen locks. Used when we want our app audio with built-in app audio
AVAudioSessionCategorySoloAmbient or the equivalent kAudioSessionCategory_SoloAmbientSound—Use this category for an application whose audio you want silenced when the user switches the Ring/Silent switch to the “silent” position and when the screen locks. This is the default category
AVAudioSessionCategoryPlayback or the equivalent kAudioSessionCategory_MediaPlayback—Use this category for an application whose audio playback is of primary importance. Your audio plays even with the screen locked and with the Ring/Silent switch set to silent.
Hint: Upload the audio file to your buzztouch account files. This is the only way Buzztouch will recognize the audio. next, add the audio file to your xcode bttouch sound folder and add all references. You should be fine!

AVAudioPlayer, using AmbientSound session, is not playing when app is in background

If this is in the apple doc then I've not been able to find it - hoping someone can help:
My app plays occasional short audio clips - I want the audio to mix in with audio playing from other apps in the background like the iPod app - but I also want it to carry on playing these audio clips when the app is running in background.
I have set "App plays audio" in the Required Background Modes settings in info.plist (the app is also using location services too so that is also set in there)
My app sets up an audio session on applicationDidFinishLaunching:
AudioSessionInitialize (NULL,NULL,NULL,NULL);
UInt32 sessionCategory = kAudioSessionCategory_AmbientSound;
AudioSessionSetProperty (kAudioSessionProperty_AudioCategory,sizeof (sessionCategory),&sessionCategory);
AudioSessionSetActive(true);
In my viewWillAppear: method in the view that is active I have:
[super viewWillAppear:animated];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
and the corresponding event handler and endReceivingRemoteControlEvents code in viewWillDisappear: as discussed in iOS 4: Remote controls for background audio
Finally I have an AVAudioPlayer, set up in the normal way, that plays a sound on certain events
bool successful = [avAudioPlayer play];
if(!successful)
NSLog(#"did not play");
When the app is in foreground the app works fine and plays the audio - but when the app goes into background and the app attempts to play a sound the return value from the [avAudioPlayer play] is NO and the sound does not play - when switched back to foreground the audio starts working again.
If when I set up the session I instead use
UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
Then the audio plays in foreground and background perfectly. But MediaPlayback is not the really the right mode for this app since I am only occasionally playing audio clips - AmbientSound is really the mode I should be using.
What am I missing? Is it just not possible to use kAudioSessionCategory_AmbientSound to play Audio in the background? If so I've not found anything in the documentation about that.
Had to submit a tech support request for this in the end.
According to Apple background playback is not supported by the AmbientSound category - you have to use MediaPlayback.
They claim this is in the documentation - I've looked again and I could not find it.
Ok so getting background sounds to mix into MediaPlayback is easy enough using kAudioSessionProperty_OverrideCategoryMixWithOthers - but I am now going to have to jump through some other hoops to replicate the other AmbientSound functionality (obeying the mute switch and not playing when locked). I really don't understand why AmbientSound is not supported playing in background - but there we go.

Resources