iphone实现声音的录制和播放

在之前iPhone播放声音文件的例子中,只是实现了声音的播放,下面主要实现声音的录制,同时播放声音。采用AVAudioRecorder进行声音的录制。

下面是实现的代码:

#import "TalkingDemoViewController.h"

@implementation TalkingDemoViewController 
@synthesize recorder; 
// Implement viewDidLoad to do additiona    l setup after loading the view, typically from a nib. 
- (void)viewDidLoad { 
    [super viewDidLoad]; 

-(IBAction)sayTalking:(id)sender 

    NSLog(@"播放声音"); 
    [self playRecord]; 
    [player play];


-(void)playRecord 

        if (player) { 
            [player release]; 
        } 
    NSArray *paths=NSSearchPathForDirectoriesInDomains( 
                                                       NSDocumentDirectory,NSUserDomainMask,YES); 
    NSString *documentsDirectory=[paths objectAtIndex:0]; 
    NSString *soundPath=[documentsDirectory stringByAppendingPathComponent:@"record.caf"]; 
    NSLog(@"logpath<<<%@",soundPath); 
        //NSString *soundPath=[[NSBundle mainBundle] pathForResource:@"record" ofType:@"caf"]; 
        NSURL *soundUrl=[[NSURL alloc] initFileURLWithPath:soundPath]; 
        player=[[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil]; 
        [player prepareToPlay]; 
        [soundUrl release];


-(IBAction)startrecording:(id)sender 

    NSLog(@"开始录音"); 
    [self beginRecord];    

-(IBAction)stoprecording:(id)sender 

    NSLog(@"停止录音"); 
    [self stopRecord]; 
}

-(void)beginRecord 

    //创建文件管理器 
     NSFileManager *fileManager = [NSFileManager defaultManager]; 
    //获取路径 
    //参数NSDocumentDirectory要获取那种路径 
    NSArray *paths=NSSearchPathForDirectoriesInDomains( 
                                                       NSDocumentDirectory,NSUserDomainMask,YES); 
    NSString *documentsDirectory=[paths objectAtIndex:0];//去处需要的路径 
    //更改到待操作的目录下 
    [fileManager changeCurrentDirectoryPath:[documentsDirectory stringByExpandingTildeInPath]]; 
    //创建文件fileName文件名称,contents文件的内容,如果开始没有内容可以设置为nil,attributes文件的属性,初始为nil 
    [fileManager createFileAtPath:@"fileName" contents:nil attributes:nil]; 
    //获取文件路径 
    NSString *soundFilePath=[documentsDirectory stringByAppendingPathComponent:@"record.caf"]; 
    NSLog(@"path>>%@",soundFilePath); 
    NSURL *fileURL=[[NSURL alloc]initFileURLWithPath:soundFilePath]; 
    AVAudioRecorder *newRecorder=[[AVAudioRecorder alloc]initWithURL:fileURL settings:nil error:nil]; 
    [fileURL release]; 
    self.recorder=newRecorder; 
    [newRecorder release]; 
    [self.recorder prepareToRecord]; 
    [self.recorder setDelegate:self]; 
    [self.recorder record]; 

-(void)stopRecord 

    if(self.recorder.recording) 
    { 
        [self.recorder stop]; 
    } 

- (void)dealloc { 
    [player release]; 
    [super dealloc]; 
}

@end

其中也要引入AVFoundation.framework组建。

源代码:http://easymorse-android.googlecode.com/svn/trunk/TalkingDemo/

你可能感兴趣的:(影音处理与播放)