點擊按鈕讓麥克風錄音,再次點擊完成錄音

 viewcontroller.h

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface ViewController : UIViewController
{
    AVAudioRecorder *audioRecorder;
    AVAudioPlayer *audioPlayer;
}

@end 

 viewcontroller.m

#import "ViewController.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIButton *playRecordBtn;
@property (weak, nonatomic) IBOutlet UIButton *recordBtn;
- (IBAction)recordBtn:(id)sender;
- (IBAction)playRecordBtn:(id)sender;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    NSArray *dirPath;
    NSString *docsDir;
    
    dirPath = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
    docsDir = dirPath[0];
    
    NSString *soundFilePath = [docsDir stringByAppendingPathComponent:@"sound.caf"];
    NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
    
    NSDictionary *recordSetting = [NSDictionary dictionaryWithObjectsAndKeys:
                                   [NSNumber numberWithInt:AVAudioQualityMin],AVEncoderAudioQualityKey,
                                   [NSNumber numberWithInt:16], AVEncoderBitRateKey,
                                   [NSNumber numberWithInt:2], AVNumberOfChannelsKey,
                                   [NSNumber numberWithFloat:16==44100.0], AVSampleRateKey,
                                   nil];
    
    NSError *err=nil;
    [[AVAudioSession sharedInstance]setCategory:AVAudioSessionCategoryPlayAndRecord error:&err];
    
    audioRecorder = [[AVAudioRecorder alloc]initWithURL:soundFileURL settings:recordSetting error:&err];
    
    if(err){
        NSLog(@"%@", [err description]);
    }else{
        [audioRecorder prepareToRecord];
    }
                               
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)playRecordBtn:(id)sender {
    
    audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:audioRecorder.url error:nil];
    audioPlayer.numberOfLoops = 0;
    [audioPlayer prepareToPlay];
    [audioPlayer play];
}

- (IBAction)recordBtn:(id)sender {
    
    if(audioPlayer.isPlaying){
        [audioPlayer stop];
    }
    
    if (!audioRecorder.isRecording) {
        [audioRecorder record];
        [sender setTitle:@"stop recording" forState:UIControlStateNormal ];
    }else{
        [audioRecorder stop];
        [sender setTitle:@"Record it" forState:UIControlStateNormal];
    }
}
@end

arrow
arrow
    文章標籤
    使用麥克風錄音
    全站熱搜
    創作者介紹
    創作者 Will 的頭像
    Will

    Will的部落格

    Will 發表在 痞客邦 留言(0) 人氣()