分享

iphone实现声音的录制和播放

 求知665 2014-10-07

#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

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多