iOS中 UIMPMediaPickerController播放系統音樂

來源:互聯網
上載者:User

iOS中 UIMPMediaPickerController播放系統音樂

布局如下:

 

引入架構:

#import

#import

遵循協議及引入標頭檔

 

#import ViewController.h#import #import @interface ViewController ()@end@implementation ViewController
點擊事件:

 

 

- (IBAction)pickMusicAction:(UIButton *)sender {        //建立一個MPMediaPickerController 並為其指定媒體類型    //媒體類型:包括音樂,音頻等    //MPMediaTypeMovie    //MPMediaTypeMusic    MPMediaPickerController *mediaPC = [[MPMediaPickerController alloc]initWithMediaTypes:(MPMediaTypeMusic)];        if (mediaPC != nil) {        NSLog(@Successfully instantiated a media picker);                // 設定相關的屬性        // 代理        mediaPC.delegate = self;        // 提示文字        mediaPC.prompt = @請選擇要播放的音樂;        // 是否允許一次選擇多個        mediaPC.allowsPickingMultipleItems = YES;                [self presentViewController:mediaPC animated:YES completion:nil];      }else{        NSLog(@Could not instantiate a media picker);    }        }

 

// 通過代理方法來擷取選中的歌曲

// MPMediaItemCollection 多媒體項集合

// MPMediaItem 單個多媒體項,如一首歌曲

// collection是一組有序的item集合

- (void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection{    NSLog(@%@,mediaItemCollection);        //MPMusicPlayerController類可以播放音樂庫中的音樂    //MPMusicPlayerController提供兩種播放器類型,一種是applicationMusicPlayer,一種是iPodMusicPlayer,這裡用iPodMusicPlayer。前者在應用退出後音樂播放會自動停止,後者在應用停止後不會退出播放狀態。    MPMusicPlayerController *musicPC = [[MPMusicPlayerController alloc]init];        //MPMusicPlayerController載入音樂不同於前面的AVAudioPlayer,AVAudioPlayer是通過一個檔案路徑來載入,而MPMusicPlayerController需要一個播放隊列,正是由於它的播放音頻來源是一個隊列,因此MPMusicPlayerController支援上一曲、下一曲等操作。        [musicPC setQueueWithItemCollection:mediaItemCollection];    [musicPC play];   }

//選中後取消動作- (void)mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker{    NSLog(@Media Picker was cancelled);        [mediaPicker dismissViewControllerAnimated:YES completion:nil];    }

最終效果:

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.