最新的設(shè)備 音頻和視頻是很常見的。在 IOS 中分別在 AVFoundation.framework 和 MediaPlayer.framewor 支持幫助下可實(shí)現(xiàn)操作。
涉及的步驟
1. 創(chuàng)建一個(gè)簡(jiǎn)單的應(yīng)用程序。
2. 選擇項(xiàng)目文件,選擇目標(biāo),然后我們添加 AVFoundation.framework 和 MediaPlayer.framework.
3. 添加兩個(gè)按鈕ViewController.xib的和播放音頻和視頻分別創(chuàng)建一個(gè)動(dòng)作。
4. 更新 ViewController.h 文件內(nèi)容如下:
#import <UIKit/UIKit.h> #import <AVFoundation/AVFoundation.h> #import <MediaPlayer/MediaPlayer.h> @interface ViewController : UIViewController { AVAudioPlayer *audioPlayer; MPMoviePlayerViewController *moviePlayer; } -(IBAction)playAudio:(id)sender; -(IBAction)playVideo:(id)sender; @end
5. 更新 ViewController.m 文件代碼內(nèi)容如下:
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } -(IBAction)playAudio:(id)sender{ NSString *path = [[NSBundle mainBundle] pathForResource:@"audioTest" ofType:@"mp3"]; audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL: [NSURL fileURLWithPath:path] error:NULL]; [audioPlayer play]; } -(IBAction)playVideo:(id)sender{ NSString *path = [[NSBundle mainBundle]pathForResource: @"videoTest" ofType:@"mov"]; moviePlayer = [[MPMoviePlayerViewController alloc]initWithContentURL:[NSURL fileURLWithPath:path]]; [self presentModalViewController:moviePlayer animated:NO]; } @end
我們需要添加音頻和視頻文件,以確保我們得到預(yù)期的輸出。
現(xiàn)在,當(dāng)我們運(yùn)行程序時(shí),我們會(huì)得到下面的輸出。

當(dāng)我們點(diǎn)擊播放視頻時(shí),我們會(huì)得到一個(gè)輸出,如下圖所示。

我們點(diǎn)擊播放音頻的時(shí)候,會(huì)聽到聲音。