Search code examples
iosobjective-ccordovaionic-frameworkcordova-plugins

How to route audio from device speaker to bluetooth speaker?


I am using AVPlayer to play music in my code. I know I can use MPVolumeView from MediaPlayer to route between speakers, but I am looking for something different(Because I am developing the application in Ionic and I am not able to find some plugin that can perform such thing, plugin which I use is cordova-plugin-media).

I have searched about how to create it and found some answers like I can switch using AVAudioSession. I am not able to find some code related to it so if anyone can help it would be great.

Another thing is that if I change this forcefully how will it behave with Control Center.


Solution

  • You can still use MPVolumeView with IONIC as plugin, you just need to control UITouchUpInside through code.

    Check this if helps.

    - (void) currentOutputs:(CDVInvokedUrlCommand*)command {
    
        if(!mpVolumeView){
            mpVolumeView = [[MPVolumeView alloc] initWithFrame:CGRectZero];
            mpVolumeView.showsVolumeSlider = FALSE;
            [self.webView.superview addSubview:mpVolumeView];
            [mpVolumeView setAlpha:0.01];
        }
    
        UIButton* btn = nil;
        for (UIView *view in [mpVolumeView subviews]){
            if ([view.class.description isEqualToString:@"MPButton"]){
                btn = (UIButton*)view;
                break;
            }
        }
    
        if(btn){
            [btn sendActionsForControlEvents:UIControlEventTouchUpInside];
        }
    }
    

    Working plugin

    https://github.com/jaymehtasa/cordova-plugin-audioroute