IPhone AudioServicesPlaySystemSound: route through the headphones?

I'm having problems using AudioServicesPlaySystemSound. Everything works fine when the output goes through the speakers. However, when the user plugs in the headphones, there is no output. Is there an easy way to tune some kind of listener so that the sound is automatically sent through the headphones when they are connected, otherwise through the speaker?

I use the following method to play short, simple AIF sound samples:

-(void)playAif:(NSString *)filename { SystemSoundID soundID; NSString *path = [[NSBundle mainBundle] pathForResource:filename ofType:@"aif"]; if (path) { // test for path, to guard against crashes AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path],&soundID); AudioServicesPlaySystemSound (soundID); } } 

I know that there must be something missing for me, a few settings that will do this. Any ideas?

+4
source share
1 answer

Thank you @ Please, indicating me the relevant part of the documents . For others with this problem, the solution is to explicitly set the session category, in my case, to the surrounding sound. This code burst from apple docs :

  UInt32 sessionCategory = kAudioSessionCategory_AmbientSound; // 1 AudioSessionSetProperty ( kAudioSessionProperty_AudioCategory, // 2 sizeof (sessionCategory), // 3 &sessionCategory // 4 ); 

So my audio playback method now looks like this:

  -(void)playAif:(NSString *)filename { // NSLog(@"play: %@", filename); SystemSoundID soundID; NSString *path = [[NSBundle mainBundle] pathForResource:filename ofType:@"aif"]; if (path) { // test for path, to guard against crashes UInt32 sessionCategory = kAudioSessionCategory_AmbientSound; // 1 AudioSessionSetProperty ( kAudioSessionProperty_AudioCategory, // 2 sizeof (sessionCategory), // 3 &sessionCategory // 4 ); AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path],&soundID); AudioServicesPlaySystemSound (soundID); } } 

It solves my problem conveniently! The only concern I am experiencing is that setting it explicitly every time I play a sound can be excessive. Does anyone know a better and safer way to install and forget it? Otherwise, it works amazingly.

+4
source

Source: https://habr.com/ru/post/1335732/


All Articles