AVFoundation(二)---MPMusicPlayerController

话不多说,直接上代码,代码中详细介绍了如何初始化,并设置一些常用的属性。

    /**
     *  MPMusicPlayerController用于播放音乐库中的音乐
     */
    /**
     *  初始化MPMusicPlayerController,类方法
     
     + (MPMusicPlayerController *)applicationMusicPlayer; 
        获取应用播放器,注意此类播放器无法在后台播放
     
     + (MPMusicPlayerController *)systemMusicPlayer     
        获取系统播放器,支持后台播放
     */
    MPMusicPlayerController *musicplayervc = [MPMusicPlayerController systemMusicPlayer];
    /**
     * MPMusicPlayerController的对象属性
     */
    //@property (nonatomic, readonly) MPMusicPlaybackState playbackState
    /*
     播放器状态,枚举类型:
     MPMusicPlaybackStateStopped:停止播放
     MPMusicPlaybackStatePlaying:正在播放
     MPMusicPlaybackStatePaused:暂停播放
     MPMusicPlaybackStateInterrupted:播放中断
     MPMusicPlaybackStateSeekingForward:向前查找
     MPMusicPlaybackStateSeekingBackward:向后查找
     */
    if (musicplayervc.playbackState == MPMusicPlaybackStateStopped) {
        NSLog(@"停止播放");
    }
    
    /*
         @property (nonatomic) MPMusicRepeatMode repeatMode
         重复模式,枚举类型:
         MPMusicRepeatModeDefault:默认模式,使用用户的首选项(系统音乐程序设置)
         MPMusicRepeatModeNone:不重复
         MPMusicRepeatModeOne:单曲循环
         MPMusicRepeatModeAll:在当前列表内循环
     */
    musicplayervc.repeatMode = MPMusicRepeatModeNone;
    
    /*
         @property (nonatomic) MPMusicShuffleMode shuffleMode
         随机播放模式,枚举类型:
         MPMusicShuffleModeDefault:默认模式,使用用户首选项(系统音乐程序设置)
         MPMusicShuffleModeOff:不随机播放
         MPMusicShuffleModeSongs:按歌曲随机播放
         MPMusicShuffleModeAlbums:按专辑随机播放
     */
    musicplayervc.shuffleMode = MPMusicShuffleModeOff;
    
    /*
        @property (nonatomic, copy) MPMediaItem *nowPlayingItem
        正在播放的音乐项
     */
    MPMediaItem *item = musicplayervc.nowPlayingItem;
    
    /*
        @property (nonatomic, readonly) NSUInteger indexOfNowPlayingItem 
        当前正在播放的音乐在播放队列中的索引
     */
    NSUInteger index = musicplayervc.indexOfNowPlayingItem;
    
    /*
        @property(nonatomic, readonly) BOOL isPreparedToPlay 
        是否准好播放准备
     */
    BOOL isOK = musicplayervc.isPreparedToPlay;
    
    /*
        @property(nonatomic) NSTimeInterval currentPlaybackTime     
        当前已播放时间,单位:秒
     */
    NSTimeInterval currentTime = musicplayervc.currentPlaybackTime;
    
    /*
        @property(nonatomic) float currentPlaybackRate     
        当前播放速度,是一个播放速度倍率,0表示暂停播放,1代表正常速度
     */
    float playrate = musicplayervc.currentPlaybackRate;
    
    /**
     *  常用的对象方法
     */
    /*
     - (void)setQueueWithQuery:(MPMediaQuery *)query     
        使用媒体队列设置播放源媒体队列
     - (void)setQueueWithItemCollection:(MPMediaItemCollection *)itemCollection     
        使用媒体项集合设置播放源媒体队列
     - (void)skipToNextItem     
        下一曲
     - (void)skipToBeginning     
        从起始位置播放
     - (void)skipToPreviousItem     
        上一曲
     - (void)beginGeneratingPlaybackNotifications     
        开启播放通知,注意不同于其他播放器,MPMusicPlayerController要想获得通知必须首先开启,默认情况无法获得通知
     - (void)endGeneratingPlaybackNotifications     
        关闭播放通知
     - (void)prepareToPlay     
        做好播放准备(加载音频到缓冲区),在使用play方法播放时如果没有做好准备回自动调用该方法
     - (void)play     开始播放
     - (void)pause     暂停播放
     - (void)stop     停止播放
     - (void)beginSeekingForward     开始向前查找(快进)
     - (void)beginSeekingBackward     开始向后查找(快退)
     - (void)endSeeking     结束查找
     */
    
    /*
        通知:
     MPMusicPlayerControllerPlaybackStateDidChangeNotification     播放状态改变
     MPMusicPlayerControllerNowPlayingItemDidChangeNotification     当前播放音频改变
     MPMusicPlayerControllerVolumeDidChangeNotification     声音大小改变
     MPMediaPlaybackIsPreparedToPlayDidChangeNotification     准备好播放
     */
    

举个例子:下边代码是写了一个播放系统音乐的功能

#import "ViewController.h"
#import <MediaPlayer/MediaPlayer.h>

@interface ViewController ()<MPMediaPickerControllerDelegate>

/**
 *  媒体选择控制器
 */
@property (strong,nonatomic) MPMediaPickerController *mediaPicker;

/**
 *  音乐播放器
 */
@property (strong,nonatomic) MPMusicPlayerController *musicPlayer;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

}
/**
 *  获得音乐播放器
 */
-(MPMusicPlayerController *)musicPlayer{
    if (!_musicPlayer) {
        _musicPlayer = [MPMusicPlayerController applicationMusicPlayer];
        _musicPlayer.repeatMode = MPMusicRepeatModeNone;
        //开启通知,否则监控不到MPMusicPlayerController的通知
        [_musicPlayer beginGeneratingPlaybackNotifications];
        //添加通知
        [self addNotification];
    }
    return _musicPlayer;
}
/**
 *  媒体选择器
 */
-(MPMediaPickerController *)mediaPicker{
    if (!_mediaPicker) {
        //初始化媒体选择器,这里设置媒体类型为音乐,其实这里也可以选择视频、广播等
        _mediaPicker = [[MPMediaPickerController alloc]initWithMediaTypes:MPMediaTypeMusic];
        //多选
        _mediaPicker.allowsPickingMultipleItems = YES;
        _mediaPicker.prompt = @"请选择要播放的音乐";

        //设置选择器代理
        _mediaPicker.delegate = self;
    }
    return _mediaPicker;
}

/*
    取得媒体队列
 */
-(MPMediaQuery *)getLocalMediaQuery{
    MPMediaQuery *mediaQueue = [MPMediaQuery songsQuery];
    for (MPMediaItem * item in mediaQueue.items) {
        NSLog(@"标题:%@,%@",item.title,item.albumTitle);
    }
    return mediaQueue;
}

/*
    取得媒体集合
 */
-(MPMediaItemCollection *)getLocalMediaItemCollection{
    MPMediaQuery *mediaQueue = [MPMediaQuery songsQuery];
    NSMutableArray *arr = [NSMutableArray array];
    for (MPMediaItem *item in mediaQueue.items) {
        [arr addObject:item];
        NSLog(@"标题:%@,%@",item.title,item.albumTitle);
    }
    MPMediaItemCollection *mediaItemCollection = [[MPMediaItemCollection alloc]initWithItems:[arr copy]];
    return mediaItemCollection;
}

#pragma mark - MPMediaPickerController代理
//选择完成
- (void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection{
    MPMediaItem *mediaItem=[mediaItemCollection.items firstObject];//第一个播放音乐
    //注意很多音乐信息如标题、专辑、表演者、封面、时长等信息都可以通过MPMediaItem的valueForKey:方法得到,但是从iOS7开始都有对应的属性可以直接访问
    //    NSString *title= [mediaItem valueForKey:MPMediaItemPropertyAlbumTitle];
    //    NSString *artist= [mediaItem valueForKey:MPMediaItemPropertyAlbumArtist];
    //    MPMediaItemArtwork *artwork= [mediaItem valueForKey:MPMediaItemPropertyArtwork];
    //UIImage *image=[artwork imageWithSize:CGSizeMake(100, 100)];//专辑图片
    NSLog(@"标题:%@,表演者:%@,专辑:%@",mediaItem.title ,mediaItem.artist,mediaItem.albumTitle);
    [self.musicPlayer setQueueWithItemCollection:mediaItemCollection];
    [self dismissViewControllerAnimated:YES completion:nil];
}
//取消选择
- (void)mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 通知
/**
 *  添加通知
 */
-(void)addNotification{
    NSNotificationCenter *notificationCenter=[NSNotificationCenter defaultCenter];
    [notificationCenter addObserver:self selector:@selector(playbackStateChange:) name:MPMusicPlayerControllerPlaybackStateDidChangeNotification object:self.musicPlayer];
}

/**
 *  播放状态改变通知
 *
 *  @param notification 通知对象
 */
-(void)playbackStateChange:(NSNotification *)notification{
    switch (self.musicPlayer.playbackState) {
        case MPMusicPlaybackStatePlaying:
            NSLog(@"正在播放...%@",self.musicPlayer.nowPlayingItem.title);
            break;
        case MPMusicPlaybackStatePaused:
            NSLog(@"播放暂停.");
            break;
        case MPMusicPlaybackStateStopped:
            NSLog(@"播放停止.");
            break;
        default:
            break;
    }
}

#pragma mark - UI事件
- (IBAction)selectClick:(UIButton *)sender {
    [self presentViewController:self.mediaPicker animated:YES completion:nil];
}

- (IBAction)playClick:(UIButton *)sender {
    [self.musicPlayer play];
}

- (IBAction)puaseClick:(UIButton *)sender {
    [self.musicPlayer pause];
}

- (IBAction)stopClick:(UIButton *)sender {
    [self.musicPlayer stop];
}

- (IBAction)nextClick:(UIButton *)sender {
    [self.musicPlayer skipToNextItem];
}

- (IBAction)prevClick:(UIButton *)sender {
    [self.musicPlayer skipToPreviousItem];
}

 

你可能感兴趣的:(AVFoundation(二)---MPMusicPlayerController)