ios --关于播放 itunes 里面的歌曲

详情见:http://www.cnblogs.com/kenshincui/p/4186022.html  写的很好

 

#import <Foundation/Foundation.h>

@protocol MyMusicPlayer <NSObject>


@optional

@optional
/**
 *  当前播放的时间
 *
 *  @param time 时间
 */
-(void)theProcess:(NSTimeInterval)time;;

/**
 *  播放状态改变
 */
-(void)playbackStateChanged;

/**
 *  音量改变
 */
-(void)playVolumeChanged;
/**
 *  歌曲改变
 */
-(void)playItemChanged;


//************************************************************
#import <Foundation/Foundation.h>
#import "MyMusicPlayer.h"
#import <MediaPlayer/MediaPlayer.h>


typedef NS_ENUM(NSInteger, playMode) {
 
    ReaptOne  = 1,
    RandomList= 2,
    ReaptList = 3,
    
};

@protocol MyMusicPlayer;

@interface KBMediaplayer : NSObject



@property (nonatomic,weak) id<MyMusicPlayer> delegate;

@property (nonatomic) MPMediaQuery *mediaSource;
@property (nonatomic, strong) NSTimer *time;
@property (nonatomic, weak) MPMusicPlayerController *musicPlayer;
@property (nonatomic, copy) NSArray *itemsFromGenericQuery;
@property (nonatomic) playMode play;

//+ (instancetype)sharedInstance;

-(void)playAction;
-(void)stopAction;
-(void)pauseAction;
-(void)playNextOne;
-(void)playLastOne;
-(void)dolloc;

//************************************************************

#import "KBMediaplayer.h"

@implementation KBMediaplayer

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.mediaSource = [[MPMediaQuery alloc] init];
        self.itemsFromGenericQuery = [self.mediaSource items];
        
        if ([[UIDevice currentDevice].systemVersion floatValue]>=8.0) {
            self.musicPlayer = [MPMusicPlayerController systemMusicPlayer];
        }else{
            self.musicPlayer = [MPMusicPlayerController iPodMusicPlayer];
        }
        
        switch (self.play) {
            case ReaptOne:
                [self.musicPlayer setRepeatMode: MPMusicRepeatModeOne];
                break;
            case ReaptList:
                [self.musicPlayer setRepeatMode: MPMusicRepeatModeAll];
                break;
            case RandomList:
                [self.musicPlayer setShuffleMode:MPMusicShuffleModeDefault];
                break;
                
            default:
                break;
        }
        [self.musicPlayer setQueueWithQuery:self.mediaSource];
        
        self.time = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateSliderValue) userInfo:nil repeats:YES];
        
        [self setNotification];
        
       
    }
    return self;
}

-(void)setNotification{
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    
    [notificationCenter
     addObserver: self
     selector:    @selector (handle_NowPlayingItemChanged)
     name:        MPMusicPlayerControllerNowPlayingItemDidChangeNotification
     object:      self.musicPlayer];//播放的项目改变时通知
    
    [notificationCenter
     addObserver: self
     selector:    @selector (handle_PlaybackStateChanged)
     name:        MPMusicPlayerControllerPlaybackStateDidChangeNotification
     object:      self.musicPlayer];//状态改变的通知
    
    [notificationCenter
     addObserver: self
     selector:    @selector (handle_PlayVolumeChanged)
     name:        MPMusicPlayerControllerVolumeDidChangeNotification
     object:      self.musicPlayer];//音量的通知
    
    [self.musicPlayer beginGeneratingPlaybackNotifications];
}
-(void)handle_NowPlayingItemChanged{
    if ([self.delegate respondsToSelector:@selector(playItemChanged)]) {
        [self.delegate playItemChanged];
    }
}
-(void)handle_PlaybackStateChanged{
    if ([self.delegate respondsToSelector:@selector(playbackStateChanged)]) {
        [self.delegate playbackStateChanged];
    }
}
-(void)handle_PlayVolumeChanged{
    if ([self.delegate respondsToSelector:@selector(playVolumeChanged)]) {
        [self.delegate playVolumeChanged];
    }
}


-(void)playAction{
        [self.musicPlayer play];
}
-(void)stopAction{
    
        [self.musicPlayer stop];
}
-(void)pauseAction{
    
        [self.musicPlayer pause];

}

-(void)changePlayerMode:(NSInteger)mode{

    switch (mode) {
        case 1:
            [self.musicPlayer setRepeatMode: MPMusicRepeatModeOne];
            break;
        case 2:
            [self.musicPlayer setShuffleMode:MPMusicShuffleModeDefault];
            break;
        case 3:
            [self.musicPlayer setRepeatMode: MPMusicRepeatModeAll];
            break;
        default:
            break;
    }
    
    
}

-(void)playAndPauseMusic
{
    MPMusicPlaybackState playbackState = [self.musicPlayer playbackState];
    
    if (playbackState == MPMusicPlaybackStateStopped ||playbackState == MPMusicPlaybackStatePaused){
        [self.musicPlayer play];
    }
    else if (playbackState == MPMusicPlaybackStatePlaying) {
        [self.musicPlayer pause];
    }
}

-(void)playNextOne{
    
        [self.musicPlayer skipToNextItem];
        if ([self.musicPlayer playbackState] == MPMusicPlaybackStateStopped ||
            [self.musicPlayer playbackState] == MPMusicPlaybackStatePaused) {
            [self.musicPlayer play];
        }
}
-(void)playLastOne{

        [self.musicPlayer skipToPreviousItem];
        if ([self.musicPlayer playbackState] == MPMusicPlaybackStateStopped ||
            [self.musicPlayer playbackState] == MPMusicPlaybackStatePaused) {
            [self.musicPlayer play];
        }
}
-(void)updateSliderValue
{
    if ([self.delegate respondsToSelector:@selector(theProcess:)]) {
        [self.delegate theProcess:self.musicPlayer.currentPlaybackTime];
    }
}
-(void)dolloc{
    [[NSNotificationCenter defaultCenter]
     removeObserver: self
     name:           MPMusicPlayerControllerNowPlayingItemDidChangeNotification
     object:         self.musicPlayer];
    
    [[NSNotificationCenter defaultCenter]
     removeObserver: self
     name:           MPMusicPlayerControllerPlaybackStateDidChangeNotification
     object:         self.musicPlayer];
    
    [[NSNotificationCenter defaultCenter]
     removeObserver: self
     name:           MPMusicPlayerControllerVolumeDidChangeNotification
     object:         self.musicPlayer];
    
    [self.musicPlayer endGeneratingPlaybackNotifications];
    [self.musicPlayer stop];
    [_time invalidate];
}

@end
//***************************
@interface ViewController ()<MyMusicPlayer>{
   
     KBMediaplayer *musicPlayer;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    musicPlayer=[[KBMediaplayer alloc]init];
    musicPlayer.delegate=self;
    
    //UITextField *txet=[[UITextField alloc]init];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.view.backgroundColor=RGB(245, 165, 45);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)buttonPress:(id)sender {
    
     [musicPlayer playAction];

}
//**************************************Appdelegate中加入以下 代码 在杀死 程序后 停止播放
- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    
    __block UIBackgroundTaskIdentifier identifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        if (identifier != UIBackgroundTaskInvalid) {
            [[UIApplication sharedApplication] endBackgroundTask:identifier];
            identifier = UIBackgroundTaskInvalid;
        }
    }];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    
    [[MPMusicPlayerController iPodMusicPlayer]pause];
    [[MPMusicPlayerController iPodMusicPlayer]stop];
}

  

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。