#import
#import
@interface AppDelegate : UIResponder < UIApplicationDelegate ,AVAudioRecorderDelegate // 録音用 ,AVAudioPlayerDelegate // 再生用 >
AppDelegate.mで
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//オーディオセッション設定
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *error = nil;
// 使用している機種が録音に対応しているか
if ([audioSession inputIsAvailable]) {
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
}
if(error){
NSLog(@"audioSession: %@ %d %@", [error domain], [error code], [[error userInfo] description]);
//return;
}
// 録音機能をアクティブにする
[audioSession setActive:YES error:&error];
if(error){
NSLog(@"audioSession: %@ %d %@", [error domain], [error code], [[error userInfo] description]);
//return;
}
UInt32 doChangeDefaultRoute = 1;
AudioSessionSetProperty (
kAudioSessionProperty_OverrideCategoryDefaultToSpeaker,
sizeof (doChangeDefaultRoute),
&doChangeDefaultRoute
);
......
}
ViewController.hで
#import
@interface ViewController : UIViewController
< AVAudioRecorderDelegate // 録音用 ,AVAudioPlayerDelegate // 再生用 >
ViewController.mで
// 録音
-(void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{
NSLog(@"録音成功");
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"録音完了" message:@"録音完了しました。" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK" , nil];
[alert show];
[recorder release];
}
-(void)recordKey{
NSLog(@"録音");
NSString *docFolder = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *soundFilePath = [NSString stringWithFormat:@"%@/sound.caf",docFolder];
NSLog(@"%@",soundFilePath);
NSURL *soundURL = [NSURL fileURLWithPath:soundFilePath];
NSLog(@"%@",soundURL);
NSError *error = nil;
AVAudioRecorder *recorder = [[AVAudioRecorder alloc] initWithURL:soundURL settings:nil error:&error];
if(error != nil){
NSLog(@"AVAudioRecorderのイニシャライズでエラー(%@)",[error localizedDescription]);
return;
}
[recorder setDelegate:self];
[recorder recordForDuration:3.0f];
}
-(IBAction)tapRecord:(id)sender{
[self recordKey];
}
// 再生
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
NSLog(@"再生成功");
[player release];
}
- (void)playKey{
NSLog(@"再生開始");
NSString *docFolder = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *soundFilePath = [NSString stringWithFormat:@"%@/sound.caf", docFolder];
NSURL *soundURL = [NSURL fileURLWithPath:soundFilePath];
if ( [[NSFileManager defaultManager] fileExistsAtPath:soundFilePath] == NO ) {
NSLog(@"ファイルがないため再生できません");
return;
}
NSError *error = nil;
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:&error];
if (error != nil) {
NSLog(@"AVAudioPlayerのイニシャライズでエラー(%@)",[error localizedDescription]);
[player release];
error=nil;
return;
}
[player setDelegate:self];
player.volume=1.0f;
[player play];
}
-(IBAction)tapPlay:(id)sender{
[self playKey];
}