AVFoundation

来源:互联网 发布:wps软件下载2016 编辑:程序博客网 时间:2024/05/16 05:08

AVFoundation原理

AVFoundation原理

例如,我要通过camera来获取一张静态图片(简单来说就是拍照),那么流程就应该是:
device(获取设备,这里为camera)-->captureinput(用device初始化一个capture input);capture(初始化一个captureoutput)-->session(把input和output加入到session,然后startrunning)-->image(用out生成一个图片)
至于图片的生成方法,下面给出:

AVCaptureConnection*videoConnection = nil;

for (AVCaptureConnection *connection in imageOutput_.connections)

{

for (AVCaptureInputPort *port in[connectioninputPorts])

{

if ([[port mediaType] isEqual:AVMediaTypeVideo] )

{

videoConnection = connection; //先找出目标connections(见图)

break;

}

}

if (videoConnection) {break; }

}

//锁定connection后就可以获取静态图了。

[imageOutput_captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRefimageSampleBuffer, NSError*error)

    {

NSDictionary *exifAttachments =(__bridgeNSDictionary*)CMGetAttachment(imageSampleBuffer,kCGImagePropertyExifDictionary,NULL);

       NSData *imageData = [AVCaptureStillImageOutputjpegStillImageNSDataRepresentation:imageSampleBuffer];

       UIImage *image = [[UIImagealloc] initWithData:imageData];

}];


最后,如果想抓取视频的话,请参考苹果的文档:

 

Startinga Recording

You startrecording a QuickTime movie using startRecordingToOutputFileURL:recordingDelegate:.You need to supply a file-based URL and a delegate. The URL mustnot identify an existing file, as the movie file output does notoverwrite existing resources. You must also have permission towrite to the specified location. The delegate must conform tothe AVCaptureFileOutputRecordingDelegate protocol,and must implement thecaptureOutput:didFinishRecordingToOutputFileAtURL:fromConnections:error: method.

AVCaptureMovieFileOutput *aMovieFileOutput = <#Get a movie file output#>;
NSURL *fileURL = <#A file URL that identifies the output location#>;
[aMovieFileOutput startRecordingToOutputFileURL:fileURL recordingDelegate:<#The delegate#>];

In theimplementation of captureOutput:didFinishRecordingToOutputFileAtURL:fromConnections:error:,the delegate might write the resulting movie to the camera roll. Itshould also check for any errors that might have occurred.

Ensuringthe File Was Written Successfully

To determinewhether the file was saved successfully, in the implementationof captureOutput:didFinishRecordingToOutputFileAtURL:fromConnections:error: youcheck not only the error, but also the value of theAVErrorRecordingSuccessfullyFinishedKey inthe error’s user info dictionary:

- (void)captureOutput:(AVCaptureFileOutput *)captureOutput
        didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL
        fromConnections:(NSArray *)connections
        error:(NSError *)error {
 
    BOOL recordedSuccessfully = YES;
    if ([error code] != noErr) {
        // A problem occurred: Find out if the recording was successful.
        id value = [[error userInfo] objectForKey:AVErrorRecordingSuccessfullyFinishedKey];
        if (value) {
            recordedSuccessfully = [value boolValue];
        }
    }
    // Continue as appropriate...

You shouldcheck the value of the AVErrorRecordingSuccessfullyFinishedKey inthe error’s user info dictionary because the file might have beensaved successfully, even though you got an error. The error mightindicate that one of your recording constraints was reached, forexample AVErrorMaximumDurationReached or AVErrorMaximumFileSizeReached.Other reasons the recording might stop are:

  • Thedisk is full—AVErrorDiskFull.

  • Therecording device was disconnected (for example, the microphone wasremoved from an iPod touch)—AVErrorDeviceWasDisconnected.

  • Thesession was interrupted (for example, a phone call wasreceived)—AVErrorSessionWasInterrupted.


1. AVFoundation

 

Build Phases => Link Binary With Libraies => + => AVFoundation.framework => add

 

firstviewcontroller.h

C代码  收藏代码
  1. #import <UIKit/UIKit.h>  
  2. #import <AVFoundation/AVFoundation.h>  
  3.   
  4. @interface FirstViewController : UIViewController  
  5. {    
  6.     __weak IBOutlet UILabel *label;  
  7.     AVAudioPlayer *player;  
  8. }  
  9.   
  10. - (IBAction)toplay:(id)sender;  
  11.   
  12. @end  
 

firstviewcontroller.m

C代码  收藏代码
  1. - (IBAction)toplay:(id)sender   
  2. {  
  3.     NSURL  *url = [NSURL fileURLWithPath:[NSString  stringWithFormat:@"%@/test.mp3",  [[NSBundle mainBundle]  resourcePath]]];  
  4.       
  5.     NSError  *error;  
  6.     player  = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];  
  7.          
  8.     player.numberOfLoops = -1;  
  9.     [player play];  
  10.       
  11.     [label setText:@"Play ..."];  
  12. }  

 

或者:

 

C代码  收藏代码
  1. NSString *path = [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"];   
  2. NSError  *error;   
  3. player = [[AVAudioPlayer alloc]initWithContentsOfURL:[[NSURL alloc]initFileURLWithPath:path]error:&error];   
  4. [player prepareToPlay];  
  5. player.numberOfLoops = -1;  
  6. [player play];  
 

test.mp3 拖放到 Supporting Files 文件夹。

 

播放,暂停和停止

C代码  收藏代码
  1. [player play];  //播放  
  2. [player pause]; //暂停  
  3. [player stop];  //停止  
 

更多功能:

 

1. 音量:

Java代码  收藏代码
  1. player.volume=0.8;//0.0~1.0之间    
 

2. 循环次数

C代码  收藏代码
  1. player.numberOfLoops = 3;//默认只播放一次 负数(-1)为无限循环  
 

3.播放位置

C代码  收藏代码
  1. player.currentTime = 15.0;//可以指定从任意位置开始播放   

 

3.1 显示当前时间

C代码  收藏代码
  1. NSLog(@"%f seconds played so  far", player.currentTime);  

 

4.声道数

C代码  收藏代码
  1. NSUInteger channels = player.numberOfChannels;//只读属性   
 

5.持续时间

C代码  收藏代码
  1. NSTimeInterval duration = player.dueration;//获取采样的持续时间    

 

6.仪表计数

C代码  收藏代码
  1. player.meteringEnabled = YES;//开启仪表计数功能  
  2. [ player updateMeters];//更新仪表读数  
  3. //读取每个声道的平均电平和峰值电平,代表每个声道的分贝数,范围在-100~0之间。  
  4. for(int i = 0; i<player.numberOfChannels;i++){  
  5. float power = [player averagePowerForChannel:i];  
  6. float peak = [player peakPowerForChannel:i];  
  7. }  
 

7. 初始化播放器  

C代码  收藏代码
  1. [player prepareToPlay];  

 

8. 判断是否正在播放

C代码  收藏代码
  1. [player isPlaying]  

 

9、代理方法

 

          加入播放出现异常,或者被更高级别的系统任务打断,我们的程序还没来得及收场就挂了,怎么办?不急,我们可以通过几个委托方法很好地处理所有的情形。

首先给player设置委托是必须的:

 

C代码  收藏代码
  1. player.delegate = self;    
C代码  收藏代码
  1. - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer*)player successfully:(BOOL)flag{  
  2.     //播放结束时执行的动作  
  3. }  
  4. - (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer*)player error:(NSError *)error{  
  5.     //解码错误执行的动作  
  6. }  
  7. - (void)audioPlayerBeginInteruption:(AVAudioPlayer*)player{  
  8.     //处理中断的代码  
  9. }  
  10. - (void)audioPlayerEndInteruption:(AVAudioPlayer*)player{  
  11.     //处理中断结束的代码  
  12. }  
  

 

 

参考:

http://blog.csdn.net/xys289187120/article/details/6595919

http://blog.csdn.net/iukey/article/details/7295962

 

视频:

http://www.youtube.com/watch?v=kCpw6iP90cY

 

 

2. AudioToolbox

 

Build Phases => Link Binary With Libraies => + => AudioToolbox.framework => add

 

firstviewcontroller.h

C代码  收藏代码
  1. #import <UIKit/UIKit.h>  
  2. #import <AudioToolbox/AudioToolbox.h>  
  3.   
  4. @interface FirstViewController : UIViewController  
  5. {    
  6. }  
  7.   
  8. - (IBAction)toplay:(id)sender;  
  9.   
  10. @end  
 

firstviewcontroller.m

C代码  收藏代码
  1. - (IBAction)toplay:(id)sender  
  2. {  
  3.     CFBundleRef mainBundle = CFBundleGetMainBundle();  
  4.     CFURLRef soundFileURLRef;  
  5.     soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"sound1", CFSTR ("wav"), NULL);  
  6.       
  7.     UInt32 soundID;  
  8.     AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);  
  9.     AudioServicesPlaySystemSound(soundID);  
  10. }  
 

原创粉丝点击