iOS - 音频和视频

音频和视频在最新设备中非常常见.在iOS中借助 AVFoundation.framework MediaPlayer.framework 分别支持它.

涉及的步骤

第1步 : 创建一个简单的基于视图的应用程序.

步骤2 : 选择你的项目文件,选择目标,然后我们应该添加 AVFoundation.framework MediaPlayer.framework .

步骤3 : 在ViewController.xib中添加两个按钮,分别创建一个播放音频和视频的动作.

步骤4 : 更新 ViewController.h 如下 :

#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 如下 :

#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

注意

我们需要添加音频和视频文件确保我们得到预期的输出.

输出

当我们运行应用程序时,我们将获得以下输出和减号;

iOS Tutorial

当我们点击播放视频时,我们会得到如图所示的输出低于&=;

iOS教程

当我们点击播放音频时,你会听到音频.