録音と再生

4203 ワード

#import "ViewController.h"
// AVFoundation 
#import 
@interface ViewController ()
{
    NSURL *recordURL;
    AVAudioPlayer *player;
    AVAudioRecorder *recorder;
}
@end

@implementation ViewController


UIControlEventTouchDownの録音を開始するにはbuttonステータスを設定します

- (IBAction)startRecord:(UIButton *)sender {
    //  
    recorder = nil;
    // 
    NSFileManager *manager = [NSFileManager defaultManager];
    // 
    [manager removeItemAtURL:_soundFileURL error:nil];
    // 
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryRecord error:nil];
    // 
     /*
     1  
     2  
     3   2
     4  
     5  ( , )
     6  
     */
    NSDictionary *setting = @{AVFormatIDKey : [NSNumber numberWithInt:kAudioFormatMPEG4AAC],
                              AVSampleRateKey : @1000,
                              AVNumberOfChannelsKey : @2,
                              AVLinearPCMBitDepthKey : @16,
                              AVLinearPCMIsBigEndianKey : @NO,
                              AVLinearPCMIsFloatKey : @NO,
                              AVEncoderAudioQualityKey : [NSNumber numberWithInt:AVAudioQualityMedium]
                              };
    // 
    recorder = [[AVAudioRecorder alloc] initWithURL:recordURL settings:setting error:nil];
    [recorder prepareToRecord];
    // 
    [recorder record];
}

UIControlEventTouchUpInsideの録音を停止するにはbuttonの状態を設定します。

- (IBAction)stopRecord:(UIButton *)sender {
    // , 
    [recorder stop];
    // 
    recorder = nil;
    // 
    [[AVAudioSession sharedInstance]setCategory:AVAudioSessionCategorySoloAmbient error:nil];
}

録音を再生する.


- (IBAction)playRecord:(UIButton *)sender {
    // 
    player = nil;
    // 
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:recordURL error:nil];
    [player prepareToPlay];
    [player play];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // 
    NSString *recordString = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/sound.acc"];
    // 
    recordURL = [NSURL fileURLWithPath:recordString];

}

@end