iOS background audio not playing

前端 未结 5 2135
悲哀的现实
悲哀的现实 2020-11-27 05:51

I have an app that uses CoreBluetooth background modes. When a certain event happens I need to play an alarm sound. Everything works fine in the foreground and

5条回答
  •  青春惊慌失措
    2020-11-27 06:45

    add a key named Required background modes in property list (.plist) file ..

    as following picture..

    enter image description here may you get help..

    and add following code in

    AppDelegate.h

    #import 
    #import 
    

    AppDelegate.m

    in application didFinishLaunchingWithOptions

    [[AVAudioSession sharedInstance] setDelegate:self];
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession sharedInstance] setActive:YES error:nil];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    
    UInt32 size = sizeof(CFStringRef);
    CFStringRef route;
    AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &size, &route);
    NSLog(@"route = %@", route);
    

    If you want changes as per events you have to add following code in AppDelegate.m

    - (void)remoteControlReceivedWithEvent:(UIEvent *)theEvent {
    
        if (theEvent.type == UIEventTypeRemoteControl)  {
            switch(theEvent.subtype)        {
                case UIEventSubtypeRemoteControlPlay:
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"TogglePlayPause" object:nil];
                    break;
                case UIEventSubtypeRemoteControlPause:
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"TogglePlayPause" object:nil];
                    break;
                case UIEventSubtypeRemoteControlStop:
                    break;
                case UIEventSubtypeRemoteControlTogglePlayPause:
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"TogglePlayPause" object:nil];
                    break;
                default:
                    return;
            }
        }
    }
    

    based on notification have to work on it..

    code.tutsplus.com provides a tutorial.

    for HandsetBluetooth you have to add following code in AppDelegate

    UInt32 size = sizeof(CFStringRef);
        CFStringRef route;
        AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &size, &route);
        NSLog(@"route = %@", route);
        NSString *routeString=[NSString stringWithFormat:@"%@",route];
        if([routeString isEqualToString:@"HeadsetBT"]){
            UInt32 allowBluetoothInput = 1;
            AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryEnableBluetoothInput,sizeof (allowBluetoothInput),&allowBluetoothInput);
        }
    

提交回复
热议问题