一.音频视频播放
1.音频播放
IOS中有三种播放音频的方式:AVAudioPlayer、音频服务、音频队列。
此文主要讲AVAudioPlayer,其他两个请见相关文章。
AVAudioPlayer在AVFoundation框架下,所以我们要导入AVFoundation.framework。
AVAudioPlayer类封装了播放单个声音的能力。播放器可以用NSURL或者NSData来初始化,要注意的是NSURL并不可以是网络url而必须是本地文件URL,因为 AVAudioPlayer不具备播放网络音频的能力,不过我们可以用过一点小手段使其具备这个能力,留待稍后讲解。
一个AVAudioPlayer只能播放一个音频,如果你想混音你可以创建多个AVAudioPlayer实例,每个相当于混音板上的一个轨道。
一、创建一个播放器
- #import <AVFoundation/AVFoundation.h>
- NSError* err;
- AVAudioPlayer* player = [[AVAudioPlayer alloc]
- initWithContentsOfURL:[NSURL fileURLWithPath:
- [[NSBundle mainBundle]pathForResource:
- @"music" ofType:@"m4a"
- inDirectory:@"/"]]
- error:&err ];//使用本地URL创建
- AVAudioPlayer* player = [[AVAudioPlayer alloc]
- initWithData:myData
- error:&err ];//使用NSData创建
我之前讲过AVAudioPlayer不可以播放网络URL,但是可以播放NSData,我们似乎受到了点启发,我们可以通过网络URL去创建NSData,然后在通过AVAudioPlayer来播放NSData,这样是不是就可以播放网络音乐了呢?但是此法并不可取,因为AVAudioPlayer只能播放一个完整的文件,并不支持流式播放,所以必须是缓冲完才能播放,所以如果网络文件过大抑或是网速不够岂不是要等很久?所以播放网络音频我们一般用音频队列。
二、播放器属性
创建一个AVAudioPlayer以后你就可以对它的各种属性进行访问或设置了 。
1.音量
- player.volume=0.8;//0.0~1.0之间
- player.numberOfLoops = 3;//默认只播放一次
- player.currentTime = 15.0;//可以指定从任意位置开始播放
- NSUInteger channels = player.numberOfChannels;//只读属性
- NSTimeInterval duration = player.dueration;//获取采样的持续时间
6.仪表计数
- player.meteringEnabled = YES;//开启仪表计数功能
- [ player updateMeters];//更新仪表读数
- //读取每个声道的平均电平和峰值电平,代表每个声道的分贝数,范围在-100~0之间。
- for(int i = 0; i<player.numberOfChannels;i++){
- float power = [player averagePowerForChannel:i];
- float peak = [player peakPowerForChannel:i];
- }
三、播放声音
准备了这么久,终于可以播放了,心情激动啊。
- [ player prepareToPlay];//分配播放所需的资源,并将其加入内部播放队列
- [player play];//播放
- [player stop];//停止
是否觉得准备了这么久,一下子就结束掉了,太快了,不用急,还有几个重点。
四、代理方法
加入播放出现异常,或者被更高级别的系统任务打断,我们的程序还没来得及收场就挂了,怎么办?不急,我们可以通过几个委托方法很好地处理所有的情形。
首先给player设置委托是必须的:
- player.delegate = self;
- - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer*)player successfully:(BOOL)flag{
- //播放结束时执行的动作
- }
- - (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer*)player error:(NSError *)error{
- //解码错误执行的动作
- }
- - (void)audioPlayerBeginInteruption:(AVAudioPlayer*)player{
- //处理中断的代码
- }
- - (void)audioPlayerEndInteruption:(AVAudioPlayer*)player{
- //处理中断结束的代码
- }
2.视频播放器
MPMoviePlayerController 与AVAudioPlayer有点类似,前者播放视频,后者播放音频,不过也有很大不同,MPMoviePlayerController 可以直接通过远程URL初始化,而AVAudioPlayer则不可以。不过大体上用起来感觉差不多。废话少说进入体验。
格式支持:MOV、MP4、M4V、与3GP等格式,还支持多种音频格式。
首先你得引入 MediaPlayer.framework.然后在使用到MPMoviePlayerController 的文件中导入相应的头文件。
一、创建
MPMoviePlayerController 类通过一个NSURL来初始化,这个URL可以使本地的,也可以是远程的。初始化需要通过 initWithContentURL 方法来实现:
- MPMoviePlayerController *moviePlayer = [ [ MPMoviePlayerController alloc]initWithContentURL:[NSURL urlWithString:@"http://"] ];//远程
- NSString* path =[ NSString stringWithFormat:@"%@/Documents/video.3gp",NSHomeDirectory()];//本地路径
- MPMoviePlayerController *moviePlayer = [ [ MPMoviePlayerController alloc]initWithContentURL:[NSURL fileURLWithPath:path]];//本地的
1.控制器样式
- moviePlayer.moviewControlMode = MPMovieControlModeDefault;
MPMovieControlModeDefault 显示播放/暂停、音量和时间控制
MPMovieControlModeVolumeOnly 只显示音量控制
MPMovieControlModeHidden 没有控制器
2.屏幕宽高比例
- moviePlayer.scallingMode = MPMovieScallingModeAspectFit;
MPMovieScallingModeNone 不做任何缩放
MPMovieScallingModeAspectFit 适应屏幕大小,保持宽高比
MPMovieScallingModeAspectFill 适应屏幕大小,保持宽高比,可裁剪
MPMovieScallingModeFill 充满屏幕,不保持宽高比
3.背景色
背景色会在电影播放器转入转出时使用,当电影不能充满整个屏幕时,也会用来填充空白区域。默认的背景色是黑色,不过你可以使用 UIColor 对象设置backgroundColor属性,来改变背景色:
- moviePlayer.backgroundColor = [UIColor redColor];
要播放电影请调用play 方法,电影播放控制器会自动将视图切换到电影播放器并开始播放:
- [ moviePlayer play ];
- [ moviePlayer stop ];
四、通知
你的程序可以配置电影播放器在何时候发送通知,包括结束加载内容、技术播放、改变宽高比等。电影播放器会将事件发送到 Cocoa 的通知中心,你可以对其进行配置,指定将这些事件转发到你的应用程序的一个对象。要接收这些通知,需要使用 NSNotificationCenter 类,为电影播放器添加一个观察者(observer):
- NSNotificationCenter* notificationCenter = [NSNotificationCenter defaultCenter];
- [ notificationCenter addObserver:self selector:@selector(moviePlayerPreloadFinish:) name:MPMoviePlayerContentPreloadDidFinishNotification object:moviePlayer ];
- -(void)moviePlayerPreloadDidFinish:(NSNotification*)notification{
- //添加你的处理代码
- }
MPMoviePlayerContentPreloadDidFinishNotification
当电影播放器结束对内容的预加载后发出。因为内容可以在仅加载了一部分的情况下播放,所以这个通知可能在已经播放后才发出。
MPMoviePlayerScallingModeDidChangedNotification
当用户改变了电影的缩放模式后发出。用户可以点触缩放图标,在全屏播放和窗口播放之间切换。
MPMoviePlayerPlaybackDidFinishNotification
当电影播放完毕或者用户按下了Done按钮后发出。
二.照相机和相册的使用
1.打开相机:
- //先设定sourceType为相机,然后判断相机是否可用(ipod)没相机,不可用将sourceType设定为相片库
- UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
- // if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
- // sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
- // }
- //sourceType = UIImagePickerControllerSourceTypeCamera; //照相机
- //sourceType = UIImagePickerControllerSourceTypePhotoLibrary; //图片库
- //sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum; //保存的相片
- UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
- picker.delegate = self;
- picker.allowsEditing = YES;//设置可编辑
- picker.sourceType = sourceType;
- [self presentModalViewController:picker animated:YES];//进入照相界面
- [picker release];
2.打开相册:(区分pad和iphone)
for iphone:
- UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
- if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
- pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
- //pickerImage.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
- pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
- }
- pickerImage.delegate = self;
- pickerImage.allowsEditing = NO;
- [self presentModalViewController:pickerImage animated:YES];
- [pickerImage release];
for ipad:
- UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
- //sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum; //保存的相片
- UIImagePickerController *picker = [[UIImagePickerController alloc] init];
- picker.delegate = self;
- picker.allowsEditing = NO;//是否允许编辑
- picker.sourceType = sourceType;
- /*
- 如果从一个导航按钮处呈现,使用:
- presentPopoverFromBarButtonItem:permittedArrowDirections:animated:;
- 如果要从一个视图出呈现,使用:
- presentPopoverFromRect:inView:permittedArrowDirections:animated:
- 如果设备旋转以后,位置定位错误需要在父视图控制器的下面方法里面重新定位:
- didRotateFromInterfaceOrientation:(在这个方法体里面重新设置rect)
- 然后再次调用:
- - (void)presentPopoverFromRect:(CGRect)rect inView:(UIView *)view permittedArrowDirections:(UIPopoverArrowDirection)arrowDirections animated:(BOOL)animated
- */
- //UIPopoverController只能在ipad设备上面使用;作用是用于显示临时内容,特点是总是显示在当前视图最前端,当单击界面的其他地方时自动消失。
- UIPopoverController *popover = [[UIPopoverController alloc]initWithContentViewController:picker];
- self.imagePicker = popover;
- //permittedArrowDirections 设置箭头方向
- [self.imagePicker presentPopoverFromRect:CGRectMake(0, 0, 300, 300) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
- [picker release];
- [popover release];
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
三.短信 电话和邮件
1、调用 自带mail
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mailto://admin@hzlzh.com"]];
2、调用 电话phone
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://8008808888"]];
3、调用 SMS
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms://800888"]];
4、调用自带 浏览器 safari
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.hzlzh.com"]];
调用phone可以传递号码,调用SMS 只能设定号码,不能初始化SMS内容。
若需要传递内容可以做如下操作:
加入:MessageUI.framework
#import <MessageUI/MFMessageComposeViewController.h>
实现代理:MFMessageComposeViewControllerDelegate
调用sendSMS函数
//内容,收件人列表
- (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSArray *)recipients
{
MFMessageComposeViewController *controller = [[[MFMessageComposeViewController alloc] init] autorelease];
if([MFMessageComposeViewController canSendText])
{
controller.body = bodyOfMessage;
controller.recipients = recipients;
controller.messageComposeDelegate = self;
[self presentModalViewController:controller animated:YES];
}
}
// 处理发送完的响应结果
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
[self dismissModalViewControllerAnimated:YES];
if (result == MessageComposeResultCancelled)
NSLog(@"Message cancelled")
else if (result == MessageComposeResultSent)
NSLog(@"Message sent")
else
NSLog(@"Message failed")
}
发送邮件的为:
导入#import <MessageUI/MFMailComposeViewController.h>
实现代理:MFMailComposeViewControllerDelegate
//发送邮件
-(void)sendMail:(NSString *)subject content:(NSString *)content{
MFMailComposeViewController *controller = [[[MFMailComposeViewController alloc] init] autorelease];
if([MFMailComposeViewController canSendMail])
{
[controller setSubject:subject];
[controller setMessageBody:content isHTML:NO];
controller.mailComposeDelegate = self;
[self presentModalViewController:controller animated:YES];
}
}
//邮件完成处理
-(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{
[self dismissModalViewControllerAnimated:YES];
if (result == MessageComposeResultCancelled)
NSLog(@"Message cancelled");
else if (result == MessageComposeResultSent)
NSLog(@"Message sent");
else
NSLog(@"Message failed");
}
四.地图和定位
iOS上使用地图只需要新建一个MKMapView,addSubView即可。这次要实现的效果如下:
1、添加地图
1.1 新一个Single View app ,选择默认项,创建后,在ViewController.h
- #import <UIKit/UIKit.h>
- #import <MapKit/MapKit.h>
- #import <CoreLocation/CoreLocation.h>
- @interface ViewController : UIViewController
- <MKMapViewDelegate, CLLocationManagerDelegate> {
- MKMapView *map;
- CLLocationManager *locationManager;
- }
- @end
1.2在ViewController.m中添加
- - (void)viewDidLoad
- {
- map = [[MKMapView alloc] initWithFrame:[self.view bounds]];
- map.showsUserLocation = YES;
- map.mapType = MKMapTypeSatellite;
- [self.view addSubview:map];
- [super viewDidLoad];
- // Do any additional setup after loading the view, typically from a nib.
- }
运行:
OMG,看到的是世界地图。怎么定位到指定的位置呢?比如定位回来伟大的祖国首都?
这里map.mapType =MKMapTypeSatellite;我用到是卫星地图,可以使用标准的地图,
map.mapType =MKMapTypeStandard;
注意,如果此时你编译有错误,请拉到博客最后查看 :5、 遇到的问题
2、定位到指定经纬度
- CLLocationCoordinate2D coords = CLLocationCoordinate2DMake(39.915352,116.397105);
- float zoomLevel = 0.02;
- MKCoordinateRegion region = MKCoordinateRegionMake(coords, MKCoordinateSpanMake(zoomLevel, zoomLevel));
- [map setRegion:[map regionThatFits:region] animated:YES];
这样,就我们就定位的了故宫了。
3、添加标注大头针
3.1 新建一个标注类:CustomAnnotation
按Command+N,继承NSObject。在CustomAnnotation.h 和CustomAnnotation.m文件添加如下代码:
- #import <Foundation/Foundation.h>
- #import <MapKit/MapKit.h>
- @interface CustomAnnotation : NSObject
- <MKAnnotation>
- {
- CLLocationCoordinate2D coordinate;
- NSString *title;
- NSString *subtitle;
- }
- -(id) initWithCoordinate:(CLLocationCoordinate2D) coords;
- @property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
- @property (nonatomic, retain) NSString *title;
- @property (nonatomic, retain) NSString *subtitle;
- @end
- #import "CustomAnnotation.h"
- @implementation CustomAnnotation
- @synthesize coordinate, title, subtitle;
- -(id) initWithCoordinate:(CLLocationCoordinate2D) coords
- {
- if (self = [super init]) {
- coordinate = coords;
- }
- return self;
- }
- @end
3.1 使用大头针,
新建个方法添加大头针的
- -(void)createAnnotationWithCoords:(CLLocationCoordinate2D) coords {
- CustomAnnotation *annotation = [[CustomAnnotation alloc] initWithCoordinate:
- coords];
- annotation.title = @"标题";
- annotation.subtitle = @"子标题";
- [map addAnnotation:annotation];
- }
调用
- CLLocationCoordinate2D coords = CLLocationCoordinate2DMake(39.915352,116.397105);
- float zoomLevel = 0.02;
- MKCoordinateRegion region = MKCoordinateRegionMake(coords, MKCoordinateSpanMake(zoomLevel, zoomLevel));
- [map setRegion:[map regionThatFits:region] animated:YES];
- [self createAnnotationWithCoords:coords];
4、定位到当前位置并获取当前经纬度
前面我们已经添加了locationManager,现在在DidViewLoad里直接调用
- locationManager = [[CLLocationManager alloc] init];
- locationManager.delegate = self;
- [locationManager startUpdatingLocation];
- - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
- [locationManager stopUpdatingLocation];
- NSString *strLat = [NSString stringWithFormat:@"%.4f",newLocation.coordinate.latitude];
- NSString *strLng = [NSString stringWithFormat:@"%.4f",newLocation.coordinate.longitude];
- NSLog(@"Lat: %@ Lng: %@", strLat, strLng);
- }
- - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
- NSLog(@"locError:%@", error);
- }
运行,允许获取当前位置,打印log
- 2012-06-28 23:58:32.237 MapDemo[8202:11603] Lat: 39.9011 Lng: 116.3000
- 2012-06-28 23:25:03.109 MapDemo[7531:11603] locError:Error Domain=kCLErrorDomain Code=1 "The operation couldn’t be completed. (kCLErrorDomain error 1.)"
定位后,移动到当前位置:
- - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
- [locationManager stopUpdatingLocation];
- NSString *strLat = [NSString stringWithFormat:@"%.4f",newLocation.coordinate.latitude];
- NSString *strLng = [NSString stringWithFormat:@"%.4f",newLocation.coordinate.longitude];
- NSLog(@"Lat: %@ Lng: %@", strLat, strLng);
- CLLocationCoordinate2D coords = CLLocationCoordinate2DMake(newLocation.coordinate.latitude,newLocation.coordinate.longitude);
- float zoomLevel = 0.02;
- MKCoordinateRegion region = MKCoordinateRegionMake(coords,MKCoordinateSpanMake(zoomLevel, zoomLevel));
- [map setRegion:[map regionThatFits:region] animated:YES];
- }
定位到了当前位置。
五.加速计和陀螺仪
1.访问加速计
UIAccelerometer类是单独存在的。要获取对此类的引用,请调用sharedAccelerometer方法:
UIAccelerometer *accelerometer=[UIAccelerometer sharedAccelerometer];
从加速计获取信息与从Core Location获取信息相似。创建一个符合UIAccelerometerDelegate协议的类,执行可以获取加速计信息的方法。
在分配委托时,需要以秒指定更新间隔。iPhone的加速计支持最高以每秒100次的频率进行轮询,但无法保证真正达到这么多次更新,或者可以精确均匀分隔这些更新。要分配委托或指定轮询间隔为每秒60次,可以如下所示:
accelerometer.delegate=self;
accelerometer.updateInterval=1.0f/60.0f;
完成之后,剩余的事情是实现加速计用于更新委托的方法,accelerometer:didAccelerate:。第二个变量包含了来自加速计的真实数据,嵌入在类UIAcceleration的一个对象中。
如前所述,iPhone加速计可以检测3个轴上的加速度,并且对使用UIAcceleration类实例的委托提供此信息。每个UIAcceleration实例都有x、y和z的属性,分别有一个带符号的浮点值。值0表示加速计在此轴上没有检测到任何运动。正值或负值表示一个方向上的力。例如,y的负值表示感受到了向下的力,这可能表示电话是纵向竖直握持的。y的正值表示在向上的方向施加了某些力,这可能意味着电话是倒置的或者电话正在向下运动。(这里有点疑问?说反了吧?)
请在头脑中牢记图15-1的示意图,并查看加速计结果。注意,在现实生活中,几乎不可能获得如此精确的值,因为加速计非常敏感,可以感知非常微笑的运动,而我们通常只能感知立体空间3个轴上的某一个微小受力。这是现实世界中的物理,而不是高中物理实验室。
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
NSString *newText=[[NSString alloc] initWithFormat:@"Max: x: %g\ty:%g\tz:
%g",acceleration.x,acceleration.y,acceleration.z];
label.text=newText;
[newText release];
}
此方法可以在每次调用时更改界面上的标签,调用此方法的频率取决于以前指定的updateInterval的值。
1,检测摇动
加速计通常用于检测摇动。与手势相似,摇动可以作为应用程序输入的一种形式。例如,对于绘图程序GLPaint,iPhone的示例代码之一,用户可以通过摇动iPhone擦除绘图,就像Etch-a-Sketch一样。摇动检测功能相对来说是微不足道的,主需要检查某个轴上的绝对值是否大于阈值(yu)。在正常使用期间,3个轴之一所注册的值通常在1.3g左右,若要远高于此值,则需要刻意施加力量。加速计好像不能注册高于2.3g左右的值。因此,请勿将阈值设置得高于此值。
要检测摇动,请检查绝对值是否大于1.5(表示轻微摇动)和2.0(表示剧烈摇动),代码如下:
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
if (fbasf(acceleration.x)>2.0 || fbasf(acceleration.y)>2.0 || fbasf(acceleration.z)>2.0 ) {
//do something here...
}
}
上述方法可以检测到任一轴上任何超过2g力的运动。通过要求用户前后摇动一定次数才能注册为一次摇动,我们可以执行更复杂的摇动检测,代码如下:
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
static NSInteger shakeCount=0;
static NSDate *shakeStart;
NSDate *now=[[NSDate alloc] init];
NSDate *checkDate=[[NSDate alloc] initWithTimeInterval:1.5f sinceDate:shakeStart];
if ([now compare:checkDate]==NSOrderedDescending || shakeStart ==nil) {
shakeCount=0;
[shakeStart release];
shakeStart=[[NSDate alloc] init];
}
[now release];
[checkDate release];
if (fbasf(acceleration.x)>2.0 || fbasf(acceleration.y)>2.0 || fbasf(acceleration.z)>2.0 ) {
shakeCount++;
if (shakeCount>4) {
//do something
shakeCount=0;
[shakeStart release];
shakeStart=[[NSDate alloc] init];
}
}
}
此方法可以查明加速计报告的值大于2的次数,如果在1.5s的时间内发送了4次,则注册为一次摇动。
2.加速计用作方向控制器
或许加速计在第三方应用程序中最常见的用法是作为游戏控制器。在游戏中不是使用按钮控制字符或对象的移动,而是使用加速计。例如,在赛车游戏中,像转动方向盘那样转到iPhone也许就可以驾驶汽车,而向前倾斜表示加速,向后倾斜表示刹车。
具体如何将加速计用作控制器,这很大程度上取决于游戏的特定机制。在很简单的情况下,可能只需要获取一个轴的值,乘以某个数,然后添加到所控制对象的坐标系中。
使用加速计作为控制器的一个棘手问题是,委托方法并不能保证以指定的间隔回调。如果告诉加速计每秒钟更新60次委托类,所能确定的仅仅是他每秒钟更新的次数绝对不会多于60次。因此不能保证每秒钟得到60次均匀分隔的更新,所以如果所做的动画是基于来自加速计的输入,那么必须要弄清楚委托方法调用之间的时间。
说明 本章中的应用程序在仿真器上不起作用,因为仿真器中没有加速计。
摇动与击碎
我们要编写一个应用程序,他在检测到摇动之后会使电话看起来和听起来好像他因为摇动而破碎一样。启动此应用程序后,程序会显示一张图片,他看起来像是iPhone的首页。
摇动电话时,发出破碎的声音,并更换图片。
然后只需触摸屏幕,就可以重置其初始状态。
创建一个基于视图的项目 ShakeAndBreak。在 15 ShakeAndBreak文件夹中找到两张图像和一个声音文件,拖到Resources文件夹中。还有一个icon.png,也添加到Resources文件夹。
展开Resources文件夹中的info.plist,在属性列表中添加一个条目,告诉应用程序不要使用状态栏。单击Information Property List行,单击出现在本行末端的按钮,添加一个新的子值,将新行的Key改为UIStatusBarHidden,然后在右键单击刚才添加的行的空Value列。此时应该出现一个上下文菜单,选择ValueType为Boolean。此行应该变为一个复选框,单击选中此复选框。最后,修改Icon File为icon.png。
然后,展开Classes文件,单击ShakeAndBreakViewControl
#define kAccelerationThreshold 2.2
#define kUpdateInterval (1.0f/10.0f)
#import <AudioToolbox/AudioToolbox.h>
@interface ShakeAndBreakViewControl
IBOutlet UIImageView *imageView;
BOOL brokenScreenShowing;
SystemSoundId soundID;
UIImage *fixed;
UIIMage *broken;
}
@property ..
@end
我们定义更新频率为1s 10次,这已经足够检测到一次摇动。通常来说,轮询时会使用能满足要求的最低频率。在将加速计用作控制器时,需要以相当快的速率轮询,通常达到每秒30次到60次更新。
打开ShakeAndBreakViewControl
单击ShakeAndBreakViewControl
- (void)viewDidLoad {
UIAccelerometer *accel=[UIAccelerometer sharedAccelerometer];
accel.delegate=self;
accel.updateInterval=kUpdateInterval;
NSString *path=[[NSBundle mainBundle] pathForResource:@"glass" ofType:@"wav"];
AudioServicesCreateSyste
self.fixed=[UIImage imageNamed:@"home.png"];
self.broken=[UIImage imageNamed:@"homebroken.png"];
imageView.image=fixed;
brokenScreenShowing=NO;
}
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
if (! brokenScreenShowing) {
if (acceleration.x >kAccelerationThreshold || acceleration.y >kAccelerationThreshold || acceleration.z
>kAccelerationThreshold) {
imageView.image=broken;
AudioServicePlaySystemSo
brokenScreenShowing=YES;
}
}
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
imageView.image=fixed;
brokenScreenShowing=NO;
}
@end
2.陀螺仪
以前在iphone中要得到加速度时,只能使用Accelerometer模块得到重力加速度分量,然后通过滤波得到加速度值。其实在ios中有一个陀螺仪模块,CoreMotion,使用更方便。
CoreMotion中主要有以下几个模块
初始化CoreMotion
- #import <CoreMotion/CoreMotion.h>
- CMMotionManager *motionManager = [[CMMotionManager alloc]init];
1. Accelerometer 获取手机加速度数据
- CMAccelerometerData *newestAccel = motionManager.accelerometerData;
- double accelerationX = newestAccel.acceleration.x;
- double accelerationY = newestAccel.acceleration.y;
- double accelerationZ = newestAccel.acceleration.z;
2. Gravity 获取手机的重力值在各个方向上的分量,根据这个就可以获得手机的空间位置,倾斜角度等
- double gravityX = motionManager.deviceMotion.gravity.x;
- double gravityY = motionManager.deviceMotion.gravity.y;
- double gravityZ = motionManager.deviceMotion.gravity.z;
获取手机的倾斜角度:
- double zTheta = atan2(gravityZ,sqrtf(gravityX*gravityX+gravityY*gravityY))/M_PI*180.0;
- double xyTheta = atan2(gravityX,gravityY)/M_PI*180.0;
zTheta是手机与水平面的夹角, xyTheta是手机绕自身旋转的角度
3. DeviceMotion 获取陀螺仪的数据 包括角速度,空间位置等
旋转角速度:
- CMRotationRate rotationRate = motionManager.deviceMotion.rotationRate;
- double rotationX = rotationRate.x;
- double rotationY = rotationRate.y;
- double rotationZ = rotationRate.z;
空间位置的欧拉角(通过欧拉角可以算得手机两个时刻之间的夹角,比用角速度计算精确地多)
- double roll = motionManager.deviceMotion.attitude.roll;
- double pitch = motionManager.deviceMotion.attitude.pitch;
- double yaw = motionManager.deviceMotion.attitude.yaw;
空间位置的四元数(与欧拉角类似,但解决了万向结死锁问题)
- double w = motionManager.deviceMotion.attitude.quaternion.w;
- double wx = motionManager.deviceMotion.attitude.quaternion.x;
- double wy = motionManager.deviceMotion.attitude.quaternion.y;
- double wz = motionManager.deviceMotion.attitude.quaternion.z;
通过陀螺仪模块可以实现模拟赛车,模拟射击等。