iOS Question Use iphone volume buttons in non-music apps. Possible solution?

miker2069

Active Member
Licensed User
Longtime User
I'm posting this in case someone else needs to know how to do this.

I'd like to use the iphone/ipad volume up and down buttons in a *non music* app. When the user presses the volume up/down buttons when my app is active/foreground, I'd really like to trigger volume up and down events on it.

I know about the technique described here to track volume level. This will return a value between 0 and 1 as the volume buttons are pushed. The problem (or challenge) is that when I get to the min or max condition of 0 or 1, I stop getting triggered events. Since my app doesn't have anything to do with music per se, I'd like to keep tracking when the user presses those buttons. A little googling revealed I could use the following:

B4X:
- (void)volumeDidChange:(NSNotification *)notification {
    [self.bi raiseEvent:nil event:@"volume_changed" params:nil];
   
}

- (void)addListener2 {
  MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame:CGRectMake(18, 340, 284, 23)];
//[self.view addSubview:volumeView];
//[self.bi.view addSubview:volumeView]; didn't quite get this working...

[NSNotificationCenter.defaultCenter
    addObserver:self
       selector:@selector(volumeDidChange:)
           name:@"AVSystemController_SystemVolumeDidChangeNotification"
         object:nil];
        
  [[MPMusicPlayerController applicationMusicPlayer] volume];
  
}


So in my code in the B4i I added:

B4X:
no.RunMethod("addListener2", Null)

Which will init the VolumeDidChangeNotification and now when I hit the minimum value of 0, I still get triggers and 0 is returned. When I get to the max of 1, I get triggers and still get 1. So I can effectively track which volume up or down button is pressed.

Note, I know I can refine this into one method, I just kept them separate for testing.

Also the line:
B4X:
[self.bi.view addSubview:volumeView];

I didn't work because the calling object is supposed to be a UIViewController (I think). I was attempting to disable the volume increase/decrease overlay. Is there a way to do this?
 
Top