iOS AVPlayer control using Bluetooth

2019-09-16 23:12发布

问题:

I am developing music player application with AVPlayer.

Now I have requirement, I want to control my Player with Bluetooth device for operations like Play, Pause, Next and back.

Please guide me, what are possible solutions.

回答1:

To control remote events the viewController that plays/controls the audio has to be the first responder so add this in viewDidAppear

- (void)viewDidAppear:(BOOL)animated
{

[super viewDidAppear:animated];
//Make sure the system follows our playback status
[[AVAudioSession sharedInstance] setDelegate: self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];

[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}

Then you need to control the events so add this code but to the same viewController although there is discussions as to the best place being the AppDelegate but this will just get you started:

- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
//if it is a remote control event handle it correctly
if (event.type == UIEventTypeRemoteControl) {
    if (event.subtype == UIEventSubtypeRemoteControlPlay) {
        [self play];
    } else if (event.subtype == UIEventSubtypeRemoteControlPause) {
         [self pause];
    } else if (event.subtype == UIEventSubtypeRemoteControlTogglePlayPause) {
         [self togglePlayPause];
    } else if (event.subtype == UIEventSubtypeRemoteControlNextTrack) {
            [self next];
        }
    } else if (event.subtype == UIEventSubtypeRemoteControlPreviousTrack) {

             [self previous];
    }
}

So the methods for play pause etc are the same methods you use to control the audio on the viewController, Now this will work only when the the VC that controls the audio is visible one option to get past this is have a shared instance mediaQueue / playerController or do it in the AppDelegate or even a subclass of UIWindow. But this should get you started and hope it helps.... let me know if you have any problems