iOS AVPlayer control using Bluetooth

孤者浪人 提交于 2019-12-11 15:59:25

问题


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



来源:https://stackoverflow.com/questions/17482608/ios-avplayer-control-using-bluetooth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!