iphone, how to play sound even in silent or mute mode? - iphone

as topic... is it possible ?
Thanks
again, I have attached the code as follows, please check which step is wrong .thanks.
//#step
AudioSessionInitialize (NULL, NULL, NULL, NULL);
AudioSessionSetActive(true);
UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
OSStatus error = AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof(sessionCategory),&sessionCategory);
if (error)
printf("ERROR AudioSessionSetProperty ! %d\n", error);
//#step
NSString* filePath = #"AlarmClockBell.caf";
[Util restoreResourceFile:filePath];
filePath =[Util getFileFullPathFromSysDoc:filePath];
NSURL *soundFileURL = [NSURL fileURLWithPath:filePath];
NSError* error ;
AVAudioPlayer * audioPalyer = [[AVAudioPlayer alloc] initWithContentsOfURL: soundFileURL error: &error];
if (nil == audioPalyer)
{
AppTrace3(self, #"Faild to play", soundFileURL, error);
return FALSE;
}
[audioPalyer prepareToPlay];
[audioPalyer setVolume: 5 ];
[audioPalyer setDelegate: self];
audioPalyer.numberOfLoops = 10;
[audioPalyer play];
thanks...

If you look in the docs under Audio Session Categories, you'll find a number of modes that you can set to tell the system how your app plans to use audio. The default is AVAudioSessionCategorySoloAmbient which tracks the ring/silent switch and the screen lock.
To have your app ignore the ring/silent switch settings, you could try changing the category:
#import <AudioToolbox/AudioToolbox.h>
AudioSessionInitialize (NULL, NULL, NULL, NULL);
AudioSessionSetActive(true);
UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
AudioSessionSetProperty (kAudioSessionProperty_AudioCategory,
sizeof(sessionCategory),&sessionCategory);
If you want to allow iPod audio to continue playing in the background, you'll also want to check kAudioSessionProperty_OverrideCategoryMixWithOthers.

As of iOS 6, there is an alternative method that's more compact than Ramin's answer.
#import <AVFoundation/AVFoundation.h>
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback
error:nil];
To allow background audio from other apps to continue playing, add the AVAudioSessionCategoryOptionMixWithOthers option:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback
withOptions:AVAudioSessionCategoryOptionMixWithOthers
error:nil];
There's further details in Apple's AVAudioSession Class Reference.

It must be, there's been a couple games I've had which (even when its in mute mode) will play sound. Unfortunately this was discovered whilst attempting to play games covertly in class.
As to how to actually do it, I really don't have any idea.

Related

Play audio when iPhone is muted [duplicate]

This question already has answers here:
iPhone - Is it possible to override silent mode or have a recursive alert sound with push notification? [closed]
(3 answers)
Closed 4 years ago.
I want to make an application which creates sound, music, or system sound when an iPhone is in silent mode. Is it possible to play any type of sound whether music or system tones when it is silent mode?
It's not advisable, but who am I to say you can't do it. You may have a good reason to be playing sound.
If you are using Audio Sessions, then include <AVFoundation/AVFoundation.h> at the start of your file and
[[AVAudioSession sharedInstance]
setCategory: AVAudioSessionCategoryPlayback
error: nil];
should do the trick. Note if you play music or sounds, then iPod playback will be paused.
Once this has been done, probably somewhere in the initialization of one of your classes that plays the sounds, you can instantiate sounds like this:
// probably an instance variable: AVAudioPlayer *player;
NSString *path = [[NSBundle mainBundle] pathForResource...];
NSURL *url = [NSURL fileURLWithPath:path];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:url];
When that's done, you can play with it any time you want with:
[player play]; // Play the sound
[player pause]; // Pause the sound halfway through playing
player.currentTime += 10 // skip forward 10 seconds
player.duration // Get the duration
And other nice stuff. Look up the AVAudioPlayer Class reference.
And for Swift 2, 3, 4.2
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
} catch {
print(error)
}
Yes you can play sound when the phone is set to vibrate.
Simply use the AVAudioPlayer class.
By default, playing an Audio Session
sound will ~not~ respect the setting
of the mute switch on the iPhone. In
other words, if you make a call to
play a sound and the silent (hardware)
switch on the iPhone is set to silent,
you’ll still hear the sound.
This is what you want. So now you know that playing an Audio Session when your phone is in silent mode will still play the sound you just need to know how to create an audio session to play the sound, like so:
taken from this website: http://iosdevelopertips.com/audio/playing-short-sounds-audio-session-services.html
SystemSoundID soundID;
NSString *path = [[NSBundle mainBundle]
pathForResource:#"RapidFire" ofType:#"wav"];
AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path],&soundID);
AudioServicesPlaySystemSound (soundID);
For this to work, you will need to import header file, and also add the AudioToolbox.framework to your project.
And that's it.
So from this answer you now know that you can play sound while the phone is on vibrate.
You don't need extra or special code to allow you to do this functionality as it already does that by default.
Pk
Works on iOS 6 and above
NSError *setCategoryErr = nil;
NSError *activationErr = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&setCategoryErr];
[[AVAudioSession sharedInstance] setActive:YES error:&activationErr];
Just put this in your viewDidLoad:
UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
AudioSessionSetProperty (kAudioSessionProperty_AudioCategory,
sizeof(sessionCategory), &sessionCategory);
For playing a sound in silent mode and even when it goes to background, try this:
Put this code in application:didFinishLaunchingWithOpitons:
[[AVAudioSession sharedInstance] setDelegate:self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive:YES error:nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
and this code in applicationDidEnterBackground:
[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
Also setup a background mode of Playing Audio/Air Play and include AVFoundation header.
for Objective C, you could play system sound with following code:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
*The system path could be modified.*
NSString *path = #"/System/Library/Audio/UISounds/begin_record.caf";
NSURL *url = [NSURL fileURLWithPath:path];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[player play];
Swift - Call this function before playing your audio/video to force playback when the phone is on silent. This also silences other audio that is currently playing.
You can change .duckOthers to .mixWithOthers if you don't want to silence other audio.
func setupAudio() {
let audioSession = AVAudioSession.sharedInstance()
_ = try? audioSession.setCategory(AVAudioSessionCategoryPlayback, with: .duckOthers)
_ = try? audioSession.setActive(true)
}

Audio played using AVAudioPlayer is working in iPhone Simulator but not in the Device

I need to play a video along with a small 2 sec audio play. Everything works fine in iPhone simulator but not in the Device. I am storing my audio file in the project bundle and playing the audio from there.
NSString *gotItsoundFilePath = [[NSBundle mainBundle] pathForResource:#"gotit" ofType:#"mp3"];
NSData *gotItsampleData = [[NSData alloc] initWithContentsOfFile:gotItsoundFilePath];
NSError *gotItaudioError = nil;
gotItAudioPlayer = [[AVAudioPlayer alloc] initWithData:gotItsampleData error:&gotItaudioError];
gotItAudioPlayer.numberOfLoops = 0;
This code works fine in iPhone Simulator when i use [gotItAudioPlayer play]; but the same build is not working in the device. Am i doing wrong somewhere? Can someone please help on this?
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayAndRecord error: nil];
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);
Put this code. before you make player object.

Control AudioSession from code

In my project i have a function that play music
-(void)playPlin {
AudioSessionSetActive(true);
// Set up audio session, to prevent iPhone from deep sleeping, while playing sounds
UInt32 category = kAudioSessionCategory_MediaPlayback;
AudioSessionSetProperty (
kAudioSessionProperty_AudioCategory,
sizeof (category),
&category
);
//UInt32 category = kAudioSessionCategory_MediaPlayback;
OSStatus result = AudioSessionSetProperty(kAudioSessionProperty_AudioCategory,
sizeof(category), &category);
if (result){
NSLog(#"ERROR SETTING AUDIO CATEGORY!\n");
}
result = AudioSessionSetActive(true);
if (result) {
NSLog(#"ERROR SETTING AUDIO SESSION ACTIVE!\n");
}
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"chimes" ofType:#"wav"];
NSData *sampleData = [[NSData alloc] initWithContentsOfFile:soundFilePath];
NSError *audioError = nil;
AVAudioPlayer *alarmAudioPlayer = [[AVAudioPlayer alloc] initWithData:sampleData error:&audioError];
[sampleData release];
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
if(audioError != nil) {
NSLog(#"An audio error occurred: \"%#\"", audioError);
}
else {
[alarmAudioPlayer play];
} }
The file play ok but i have three issue:
1.how can I make that the audio file starts not from the beginning but from the number of second that i pass? for example, if i step value 300 audio file should start from the second 300 of it
2.How can i set volume of audio file?
3.How can i set loop property of it?
thank in advance
This is all pretty clearly laid out in the documentation.
1) Use the playAtTime: method call instead of play. Pass the time in seconds.
2) Set the volume property on the AVAudioPlayer. Note that this is the gain of the player, and will be modulated with the current system volume.
3) Set the numberOfLoops property. Assign a huge value like NSIntegerMax to keep looping indefinitely.

How to use MPMusicPlayerController with AVAudioPlayer

I am trying to play an in app audio with ipod the code I am using to play the audio file is:
Code:
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
UInt32 doSetProperty = 1;
AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryMixWithOthers, sizeof(doSetProperty), &doSetProperty);
[[AVAudioSession sharedInstance] setActive: YES error: nil];
if(error)
{
NSLog(#"Some error happened");
}
NSString *path = [[NSBundle mainBundle] pathForResource:effect ofType:type];
myPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
myPlayer.delegate = self;
myPlayer.numberOfLoops = -2;
myPlayer.volume = 1.0f;
[myPlayer play];
and to play the ipod music I am using
Code:
player = [MPMusicPlayerController iPodMusicPlayer];
My ipod plays fine until the audio starts playing but once the audio stops I am not able to get back to the ipod to play. I am using
Code:
NSString *value = [[NSUserDefaults standardUserDefaults] stringForKey:#"sound"];
if([value compare:#"ON"] == NSOrderedSame && myPlayer != nil)
{
[myPlayer stop];
[myPlayer release];
myPlayer = nil;
}
NSError *error = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&error];
if(error)
{
NSLog(#"Some error happened");
}
to stop the audio and then just call
Code:
[player play];
to play the ipod music but it does not play the music, it says the title to be null.
I would really appreciate if some one could help me with this.
Regards,
Ankur
I suggest moving the audio session setup (including the Ambient category) to your application delegate's didFinishLaunchingWithOptions and not using the Playback category at all. You can still play AVAudio sounds just fine with the Ambient setting.
If you want to kill iPod music whenever you play AV sounds, then you should only be using the Playback category. (I'm not exactly sure what you're trying to do.)
The error that you're getting when you try to resume the iPod music suggests that your MPMusicPlayerController object resets its song queue when it is stopped by the AVAudio sounds, and that you'll have to set up the MP player again. "Title is null" definitely sounds like a dangling pointer or the like in the MP player.
It's not possible to play iPod audio in AVAudioPlayer. You need to convert the library Asset link from ipod, using *AVURLAsset to an mp3 or wav and save it to the documents library. IOS.5 currently has a bug in the conversion (AudioExportSession) from ipod to mp3 file, so it's NOT POSSIBLE. Sorry.
You need to resume iPod player after myPlayer finish playing.
-(void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
[player play];
}

how to route iPhone audio to the bluetooth headset

I'm attempting to output audio to the bluetooth headset (not A2DP) using AVAudioPlayer, AVAudioSession and AudioSessionSetProperty.
There seems to be functions to select the bluetooth headset as input (kAudioSessionProperty_OverrideCategoryEnableBluetoothInput), but no equivalent for setting the output. This is done in the Voicemail app, where you can select the headset, handset speaker or speaker phone. I've tried various combinations of SessionCategories and the AudioSession properties, but I just can't seem to hit on an approach that works.
I'm sure someone has figured this out, care to share an example?
This little test worked for me... it involves setting up the bluetooth headset as the input also (not sure if that's what you want). Sorry about the crappy formatting on the code...
// create and set up the audio session
AVAudioSession* audioSession = [AVAudioSession sharedInstance];
[audioSession setDelegate:self];
[audioSession setCategory: AVAudioSessionCategoryPlayAndRecord error: nil];
[audioSession setActive: YES error: nil];
// set up for bluetooth microphone input
UInt32 allowBluetoothInput = 1;
OSStatus stat = AudioSessionSetProperty (
kAudioSessionProperty_OverrideCategoryEnableBluetoothInput,
sizeof (allowBluetoothInput),
&allowBluetoothInput
);
NSLog(#"status = %x", stat); // problem if this is not zero
// check the audio route
UInt32 size = sizeof(CFStringRef);
CFStringRef route;
OSStatus result = AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &size, &route);
NSLog(#"route = %#", route);
// if bluetooth headset connected, should be "HeadsetBT"
// if not connected, will be "ReceiverAndMicrophone"
// now, play a quick sound we put in the bundle (bomb.wav)
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef soundFileURLRef;
SystemSoundID soundFileObject;
soundFileURLRef = CFBundleCopyResourceURL (mainBundle,CFSTR ("bomb"),CFSTR ("wav"),NULL);
AudioServicesCreateSystemSoundID (soundFileURLRef,&soundFileObject);
AudioServicesPlaySystemSound (soundFileObject); // should play into headset
Hope that helps!
I was able to get this working, but it took some doing. I've pieced together the pertinent piece of code here:
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&err];
UInt32 allowBluetoothInput = 1;
AudioSessionSetProperty(
kAudioSessionProperty_OverrideCategoryEnableBluetoothInput,
sizeof (allowBluetoothInput),
&allowBluetoothInput);
It is also possible to which sources are available and switch between bluetooth, a headset, handset or the speakerphone but things become very involved at that point. The audio source manager I ultimately wrote was over 700 lines.