Sound does not play on iPad speaker but works fine on headphones and on the iPod Touch/iPhone speakers - ios

I know this is a question has been asked for many times, and I have checked most of the answers related in SO, but I have no luck finding the right answer to my problem.
Here is the problem:
I tried to play a mp3 file (just 2 seconds at most) in a game when some event is triggered, and I use the AudioPlayer to do so, below is the code blocks:
NSError *error;
AVAudioPlayer *audioPlayer = [[[AVAudioPlayer alloc] initWithContentsOfURL:[[NSBundle mainBundle] URLForResource: #"ding" withExtension: #"mp3"] error:&error] autorelease];
if (error) {
NSLog(#"Error creating audio player: %#", [error userInfo]);
}
else {
BOOL success = [audioPlayer play];
// This always is "Play sound succeeded"
NSLog(#"Play sound %#", success ? #"succeeded" : #"failed");
}
When I ran this code in iPhone 4s, iTouch 3/4, the sound always played well and clear, but in iPad 1 or iPad2, there is no sound out from speaker. But when I plugged in my headphone, weird thing happened that there is sound from my headphone! The iPad is not in mute mode and the URL is correct.
I am confused why this happened.
PS: I tried the following code (got from HERE) to output the audio output port type:
CFDictionaryRef asCFType = nil;
UInt32 dataSize = sizeof(asCFType);
AudioSessionGetProperty(kAudioSessionProperty_AudioRouteDescription, &dataSize, &asCFType);
NSDictionary *easyPeasy = (NSDictionary *)asCFType;
NSDictionary *firstOutput = (NSDictionary *)[[easyPeasy valueForKey:#"RouteDetailedDescription_Outputs"] objectAtIndex:0];
NSString *portType = (NSString *)[firstOutput valueForKey:#"RouteDetailedDescription_PortType"];
NSLog(#"first output port type is: %#!", portType);
When I plugged in my headphone, the output was "first output port type is headphone!" and when I unplugged it , the output turned out to be "first output port type is speaker!"
It would be great is someone can offer some help or advice.

There is a code change solution to this, but also an end-user solution: turn the 'Ring/Silent switch' to on. Specifically, the problem is that the default setting of AVAudioSessions, AVAudioSessionCategorySoloAmbient, is to be silent if the phone is in silent mode.
As mentioned by the original poster, you can override this behavior by calling:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
AVAudioSession Reference recommends setting the AVAudioSessionCategoryPlayback category:
For playing recorded music or other sounds that are central to the successful use of your app.

To update #JonBrooks answer above with Swift 2 syntax, I put the following in my viewDidLoad() to override the silent switch and get my sound to play:
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
} catch let error as NSError {
print(error)
}

Solution found!
After I added this line of code before playing, the sound finally is played out from speaker
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
I now still do not understand why, and I will dig into it.:)

Related

iOS: How to play buffering audio in bluetooth headset in my music app?

I am currently doing one music app. in that i need to play buffering
audio song in blue tooth headset. i searched for code past 1 day. but
i can't. please give solution how to add this in my music app.
One more thing i need to play that audio in bluetooth headset while iphone is in backeground mode and screen lock mode.
AVAudioSession* audioSession = [AVAudioSession sharedInstance];
//[audioSession setDelegate:self];
NSError *error;
[audioSession setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionAllowBluetooth error:&error];
[audioSession setActive: YES error: nil];
// 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 ("sample"),CFSTR ("m4a"),NULL);
AudioServicesCreateSystemSoundID (soundFileURLRef,&soundFileObject);
AudioServicesPlaySystemSound (soundFileObject); // should play into headset
I have added this code in my music app. but this code is for Bundle audio file. but i need buffering audio. if it is not possible please tell is my code is correcte to play local audio file through blue tooth headset.?
From what i read in the documentation , setting the category for the audio session should be
AVAudioSessionCategoryPlayAndRecord
or
AVAudioSessionCategoryRecord
if setting the option to
AVAudioSessionCategoryOptionAllowBluetooth
so you should change that, another thing when i look at the enum: AVAudioSessionCategoryOptions the option to bluetooth is __TVOS_PROHIBITED but i don't know the alternative...

AVAudioPlayer does not audibly play, throws no errors, calls no delegate method

Encountering a very weird issue. I'm trying to use AVAudioPlayer to play a simple sound file from disk. I maintain a strong reference to it via a property so ARC doesn't kill it prematurely. As I said in the title, I get no sound, errors and no delegate methods are called--including didFinishPlaying (which I would expect). The only thing that seems to "happen" is I hear two quiet clicks...
Now this is the weird part...if I set a breakpoint just before [_player play], then step over, the audio plays fine!! This basically confirms to me that I have set things up correctly, and makes me think that something else is stepping on the shared AVAudioSession from another thread? I'm not sure. The total lack of delegate calls is very odd--it seems that something should be called whenever AVAudioPlayer finishes.
I am also using OpenEars for speech recognition, but I call suspendListening on it before attempting to play the audio. I have also tried disabling OpenEars entirely, to try and isolate it as a cause--but this had no effect, either. Very perplexing. Appreciate any help!
-(void)playAudioNoteWithPath:(NSString *)filePath
{
NSError *error = nil;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord
withOptions:AVAudioSessionCategoryOptionAllowBluetooth
error:&error];
if (error) {
DLog(#"ERROR setting audio session category: %#", [error localizedDescription]);
}
NSURL *URL = [NSURL URLWithString:filePath];
if (!URL) {
DLog(#"No file path!!");
}
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:URL
error:&error];
if (error) {
DLog(#"ERROR initializing audio player: %#", [error debugDescription]);
}
_player.delegate = self;
[_player prepareToPlay];
// Setting a breakpoint here will cause playback to succeed.
if (![_player play]) {
DLog(#"ERROR playing!!");
}
}
Well, I seem to have found a fix, though I'm not sure why...since it's not that much code, I just moved it into the calling class. So the calling class now plays AudioNotes directly, instead of AudioNotes playing themselves. Now it works.

iOS - Unable to play a sound in background

I'm currently trying to implement a system like the alarm one to alert the phone when an event occurred (in my case a bluetooth event). I want this alert to occur even if the phone is in silent and in background.
I create a local notification but i can't get sound played if the phone is in silent mode (which seems to be normal since we put the phone in silent).
So i tried to manage the sound by myself and i'm struggling with playing sound in background. So far i implement the "App plays audio or streams audio/video using AirPlay" key in my plist and i'm using this code.
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *error = nil;
BOOL result = [audioSession setActive:YES error:&error];
if ( ! result && error) {
NSLog(#"Error For AudioSession Activation: %#", error);
}
error = nil;
result = [audioSession setCategory:AVAudioSessionCategoryPlayback error:&error];
if ( ! result && error) {
NSLog(#"Error For AudioSession Category: %#", error);
}
if (player == nil) {
NSString *path = [[NSBundle mainBundle] pathForResource:#"bell" ofType:#"wav"];
NSURL *url = [NSURL fileURLWithPath:path];
NSError *err = nil;
player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&err];
if(err)
{
NSLog(#"Error Player == %#", err);
}
else {
NSLog(#"Play ready");
}
}
[player prepareToPlay];
[player setVolume:1.0];
if([player play])
{
NSLog(#"YAY sound");
}
else {
NSLog(#"Error sound");
}
The sound works great in foreground, even in silent mode, but i got no sound at all in background. Any ideas ?
Thanks
EDIT:
Finally i got it working with the above code. The only missing point is that i was trying to play the sound in somewhat appeared to be a different thread, when i play it right in my bluetooth event and not my function call it's working.
An app that plays audio continuously (even while the app is running in the background) can register as a background audio app by including the UIBackgroundModes key (with the value audio) in its Info.plist file. Apps that include this key must play audible content to the user while in the background.
Apple reference "Playing Background Audio"
Ensuring That Audio Continues When the Screen Locks
Found here
I'm not sure if your problem is that you have not configure correctly the audio session output. I had similar problem while playing .wav in my app. I only listened them with earphones. This method helped me:
- (void) configureAVAudioSession {
//get your app's audioSession singleton object
AVAudioSession *session = [AVAudioSession sharedInstance];
//error handling
BOOL success;
NSError* error;
//set the audioSession category.
//Needs to be Record or PlayAndRecord to use audioRouteOverride:
success = [session setCategory:AVAudioSessionCategoryPlayAndRecord
error:&error];
if (!success) NSLog(#"AVAudioSession error setting category:%#",error);
//set the audioSession override
success = [session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker
error:&error];
if (!success) NSLog(#"AVAudioSession error overrideOutputAudioPort:%#",error);
//activate the audio session
success = [session setActive:YES error:&error];
if (!success) NSLog(#"AVAudioSession error activating: %#",error);
else NSLog(#"audioSession active"); }
Try it out!
You need to make couple of changes in plist file.
for enabling sound when the app enter's Background.
1) Set Required background mode to App plays audio
2) set Application does not run in background to YES.
NSError *setCategoryErr = nil;
NSError *activationErr = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&setCategoryErr];
[[AVAudioSession sharedInstance] setActive:YES error:&activationErr];
Then, you need to write these much code in AppDelegate
Now, you can easily run audio while phone screen locks or in background.
It works fine for me. :)
for more please refer to Playing Audio in background mode and Audio Session Programming Guide

AVAudioPlayer intermittently wont play sound

I have a music player app on ipad. I download m4a files from a server and save them to doc dir. I also use Core Data to save the playlist info. I have over 1000 songs and my table loads perfectly and plays perfectly. I can play the playlists thru with no problems. BUT... every once in a while one song does not play. NO SOUND! I can press the cell to play the song or goto the next song and everything works again. So this problem is random and intermittent. It's never the same song that gets stuck. I cant give you any debug statements, cus like I said, it's so random and intermittent that it's hard to duplicate. I'm wondering if it's an ARC problem. Please help, as this app is going to production very soon.
Relative code:
// setup music session
NSError *error = nil;
[[AVAudioSession sharedInstance] setDelegate: self];
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &error];
[[AVAudioSession sharedInstance] setActive: YES error: &error];
NSLog(#"error AVAudioSession:%#", [error description]);
AVAudioPlayer *player = [[AVAudioPlayer alloc] init];
NSString *fullPath = fullPath = [self.docDirPath stringByAppendingPathComponent:filename];
NSURL *musicFileURL = [[NSURL alloc] initFileURLWithPath:fullPath];
// getting song from docDir
NSData *songData = [[NSData alloc] initWithContentsOfURL:musicFileURL];
player = [player initWithData:songData error:&error];
NSLog(#"error player reg:%#", [error description]);
//NSLog(#"playing %# at index:%d", musicFileURL, index);
self.appPlayer = player;
[self.appPlayer prepareToPlay];
[self.appPlayer setEnableRate: YES];
[self.appPlayer setDelegate: self];
[self.appPlayer play];
If you use ARC a good point to start to solve your problem is to watch the reference counting in Instruments. I had the problem as well. None of my files were playing. I've seen in Instruments that the AVAudioPlayer instance was released BEFORE the sound started to play. At least it looked like it was released. After i've stored the reference of AVAudioPlayer in the core data model the bug was fixed! In another project without ARC the same code did work without storing the reference.
or you can try to use strong instead of retain in the property declaration
#property(nonatomic, strong) AVAudioPlayer *player;

Starting AVAudioPlayer when application is in background

I have an application with App plays audio and App provides Voice over IP services options configured in the .plist.
The application is receiving socket events (even in background) and regarding the events, plays sound. When the application is in foreground, all is ok. When the app is in background, the app is triggered, the play method of the player is called, but without sound.
I have tried many sample code from Internet but nothing is working. I have tried to start playing sound in foreground and then move my app in background and it's working.
What is the problem to start playing a sound when the app is in background?
Here's my code handling an event when my app is triggered in background:
NSError *error;
NSURL *audioFileLocationURL = [[NSBundle mainBundle] URLForResource:#"HeadspinLong" withExtension:#"caf"];
if (audioPlayer != nil) return;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileLocationURL error:&error];
audioPlayer.delegate=self;
if (error) {
NSLog(#"%#", [error localizedDescription]);
}
audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
[audioSession setActive: YES error: &error];
audioSession.delegate=self;
if (error) {
NSLog(#"");
}
Seems like an obvious question, but are you actually calling the play method on the audioPlayer object in your real-life application? Probably at the end of background event handler?
i.e. [audioPlayer play];
For my understanding it seems not possible to start playing a music when the app is in background... It is only possible to continue playing an existing played music in background

Resources