Thursday, May 21, 2015

Swift: Remote control buttons for audio Session on lock screen

Make a file to subclass the UIApplication

make the class to respond to events

import UIKit
import Foundation
@objc(MyTest2) class MyTest2: UIApplication
{
    
    
   override func canBecomeFirstResponder() ->Bool{
        return true
    }
   override func remoteControlReceivedWithEvent(event: UIEvent) {
    }
    

}

and use the class in main.m
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#import "test3-swift.h"
int main(int argc, char * argv[]) {
    @autoreleasepool {
        return UIApplicationMain(argc, argv, NSStringFromClass([MyTest2 class]), NSStringFromClass([AppDelegate class]));
    }
}

and now activate the audioSession and use MPNowPlayingInfoCenter class. Make sure audioSession is not mixing with other.
I have used it in a view controller file

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    /*
     *  Without some sort of
     *  audio player, the remote
     *  remains unavailable to this
     *  app, and the previous app will
     *  maintain control over it.
     */
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(beginReceivingRemoteControlEvents)]){
        [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
        [self becomeFirstResponder];
    }
    
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    
    if(![[AVAudioSession sharedInstance] setActive:YES error:nil])
    {
        NSLog(@"Failed to set up a session.");
    }

    _player = [[AVPlayer alloc] initWithURL:[NSURL URLWithString:@"http://stream.jewishmusicstream.com:8000"]];
    
    /*  Kicking off playback takes over
     *  the software based remote control
     *  interface in the lock screen and
     *  in Control Center.
     */
    
    [_player play];
    
    
    Class playingInfoCenter = NSClassFromString(@"MPNowPlayingInfoCenter");
    
    if (playingInfoCenter) {
        
        
        NSMutableDictionary *songInfo = [[NSMutableDictionary alloc] init];
        
        
        MPMediaItemArtwork *albumArt = [[MPMediaItemArtwork alloc] initWithImage: [UIImage imageNamed:@"abc.jpg"]];
        
        [songInfo setObject:@"Audio Title" forKey:MPMediaItemPropertyTitle];
        [songInfo setObject:@"Audio Author" forKey:MPMediaItemPropertyArtist];
        [songInfo setObject:@"Audio Album" forKey:MPMediaItemPropertyAlbumTitle];
        [songInfo setObject:albumArt forKey:MPMediaItemPropertyArtwork];
        [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo];
        
        
    }
    
    
}


No comments:

Post a Comment