iOS--播放音訊、視訊(1:AVAudioPlayer 2:MPMoviePlayerViewController)
阿新 • • 發佈:2019-01-10
在iOS中有兩種方式可以播放音訊視訊。
一:AVAudioPlayer。它只能播放本地的音訊,不能網路音訊(即不能線上播放)MP3
1:首先要手動匯入音訊的框架 AVFoundation.framework。(iOS7.0以後,不用在手動匯入了,它自動已經包含了此框架)
2:包含標頭檔案 #import<AVFoundation/AVFoundation.h>
二:MPMoviePlayerViewController(帶VIEW,有檢視)和MPMoviePlayerController(無檢視,預設VIEW的大小為0)它不僅能播放本地音訊又可以播放網路音訊和視訊
注意:它支援的格式並不是很多,所以有些常用的rmvb等格式不支援。
1:手動匯入類庫:MediaPlayer.framework 。
2:包含標頭檔案 #import<MediaPlayer/MediaPlayer.h>
/* 注意MPMoviePlayerViewController,只支援MP4,MP3 1.問題:系統自帶的MPMoviePlayerViewController,當程式進入後臺的時候就會自動銷燬。如何讓其保持狀態進入後臺前的狀態? 原因:當系統進入後臺的時候會發出通知:UIApplicationDidEnterBackgroundNotification,而系統的MPMoviePlayerViewController會自動監聽該通知,當監聽到進入後臺的這個通知後,MPMoviePlayerViewController會呼叫方法銷燬。 解決方法:移除通知 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil]; //說明:移除self監聽的名稱為UIApplicationDidEnterBackgroundNotification的通知,object引數為空。 */
AZMyMoviePlayViewController:
#import <MediaPlayer/MediaPlayer.h>
@interface AZMyMoviePlayViewController : MPMoviePlayerViewController
@end
#import "AZMyMoviePlayViewController.h" @interface AZMyMoviePlayViewController () @end @implementation AZMyMoviePlayViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. <span style="color:#ff0000;">//移除程式進入後臺的通知</span> [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil]; } #pragma mark -- 播放介面只支援橫屏 -(NSUInteger)supportedInterfaceOrientations { return UIInterfaceOrientationMaskLandscape; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. }
AZRootViewController:
關鍵程式碼
//取出模型
AZMyVideoModel *video=self.voideListArray[indexPath.row];
NSString *videoUrlStr=[NSString stringWithFormat:@"%@%@",WEBPATH,video.url];
NSLog(@"%@",videoUrlStr);
NSURL *url=[NSURL URLWithString:videoUrlStr];
//建立播放檢視控制器
AZMyMoviePlayViewController *playVC=[[AZMyMoviePlayViewController alloc] initWithContentURL:url];
[email protected]"播放介面";
[self.navigationController pushViewController:playVC animated:YES];