- iOS 教程
- iOS - 主页
- iOS - 开始使用
- iOS - 环境设置
- iOS - Objective-C 基础知识
- iOS - 第一个 iPhone 应用程序
- iOS - 操作和出口
- iOS - 委托
- iOS - UI 元素
- iOS - 加速计
- iOS - 通用应用程序
- iOS - 相机管理
- iOS - 位置处理
- iOS - SQLite 数据库
- iOS - 发送电子邮件
- iOS - 音频和视频
- iOS - 文件处理
- iOS - 访问地图
- iOS - 应用内购买
- iOS - iAd 集成
- iOS - GameKit
- iOS - 情节提要
- iOS - 自动布局
- iOS - Twitter 和 Facebook
- iOS - 内存管理
- iOS - 应用程序调试
- iOS 实用资源
- iOS - 快速指南
- iOS - 实用资源
- iOS - 讨论
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
注意
我们需要添加音频和视频文件以确保获得预期的输出。
输出
当我们运行此应用程序时,将获得以下输出 −
当我们单击播放视频时,将获得如下所示的输出 −
当我们单击播放音频时,你将听到音频。
广告