can I play a sound while the iPhone is sleeping? - iphone

How can I play a custom, looping sound (from my app, while my app is open) while the iPhone is sleeping?
I'm using this code to play a audio file:
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"sample_name" ofType:#"wav"];
NSData *sampleData = [[NSData alloc] initWithContentsOfFile:soundFilePath];
NSError *audioError = nil;
// Set up the audio player
testAudioPlayer = [[AVAudioPlayer alloc] initWithData:sampleData error:&audioError];
[sampleData release];
if(audioError != nil) {
NSLog(#"An audio error occurred: \"%#\"", audioError);
}
else {
[testAudioPlayer setNumberOfLoops: -1];
[testAudioPlayer play];
}
But it doesn't play if the iPhone is sleeping.
Pandora has this ability, along with other similar apps.

If you are playing a sound when the phone goes to sleep, you will continue to run in the background as Pandora and others do.
If you are not playing a sound when the user puts the device to sleep, you will be suspended.
There's a reference in this answer to the apple documentation for this.
Play sound with screen turned off / don't let iPhone go to sleep

Try registering for a local notification.

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)
}

AVAudioPlayer Does not work on iPhone 5

Has anyone experienced issues with the AVAudioPlayer using an iPhone 5? My code has worked properly on the iPhone 4, iPhone 4S, and iPad (3rd gen) but it is randomly not working on the iPhone 5 now. I saw this question but no one addressed the actual issue:
AVAudioPlayer is not working in iPhone 5
NSURL *soundURL = [self urlForAlarmSong:songKey];
NSError *err;
self.audioAlert = [[[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:&err] autorelease];
[self.audioAlert prepareToPlay];
currentVolume=[MPMusicPlayerController applicationMusicPlayer].volume;
[[MPMusicPlayerController applicationMusicPlayer] setVolume:1.0];
[self.audioAlert play];
audioAlert is an AVAudioPlayer i've declared in my header with (retain,nonatomic). The err variable is null everytime, even when it does not play on an iPhone 5. This code works flawlesly every time on an iPhone 4, iPhone 4S, and iPad (3rd gen).
Does anyone have any ideas?? Thanks
-(void)viewDidLoad
{
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"click2" ofType:#"mp3"]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
if(error)
{
NSLog(#"error in audio player:%#",[error localizedDescription]);
}
else
{
audioPlayer.delegate=self;
[audioPlayer prepareToPlay];
}
}
on button action,
-(IBAction)SoundButton:(id)sender
{
[audioPlayer play];
}
In your .h File, don't forget to import
#import AVFoundation/AVFoundation.h
and add a delegate AVAudioPlayerDelegate.
Make sure that the device's sound switch is not in "mute" and the volume is high enough.
Looks pretty obvious but it can save hours of stress.

Error 24 (Too many open files) - iPhone

I recently implemented sounds into my game. Every time the user touches the screen, an arrow is shot, and a sound is played. I am using the following code to play the sound:
- (void)arrowShoot {
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/arrow.mp3", [[NSBundle mainBundle] resourcePath]]];
arrowShootPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
if (arrowShootPlayer != nil) {
[arrowShootPlayer play];
}
}
The reason I was allocating memory to the arrowShootPlayer every time is because the user can tap the screen rapidly, and I want the sounds to overlap. Otherwise, the sound only plays once the previous one has finished playing.
Anyway, I am getting this error:
<com.apple.main-thread> shm_open failed: "AppleAudioQueue.36.5755" (23) flags=0x2 errno=24
Once I get this error, the sounds stop being played. Everything else is fine, just the arrow sounds stop playing.
Is there a better way of playing 'overlapping' sounds like this on the iPhone, or is there a way around this error??
Thanks
if it is the same audio always, use the playing from memory buffer instead of opening the files. Declare some local buffer:
NSData* data;
then in your method:
if(!data) {
data = [NSData dataWithContentsOfURL:url options:NSDataReadingMappedIfSafe error:&err];
}
arrowShootPlayer = [[AVAudioPlayer alloc] initWithData:data error:nil];
if (arrowShootPlayer) {
[arrowShootPlayer play];
}

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 do I keep music playing after the user presses the hold button on the iPhone?

Hey guys how can I make an app keep playing an mp3 after pressed the hold/power button.
Here is the code I use for preparing the AVAudioPlayer:
- (void)PrepareAudio:(int)index
{
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"%#",[_Audio objectAtIndex:Game]] ofType:#"mp3"];
NSURL *newURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
MusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: newURL error: nil];
[newURL release];
[MusicPlayer setVolume: 1.5];
}
And this is the code when I press the button play:
- (IBAction)PushPlay: (id)sender
{
if(!MusicPlayer.playing)
[MusicPlayer play];
}
Best Regards
Carlos Vargas
If you are holding long enough to turn the device off, then there is no way. If you are pressing the button to lock the screen, the music can be played. Why don't you put some code up and let us see what you have tried. Hint: The answer lies within the Audio playback categories.