1. 程式人生 > >ios20-錄製音訊(播放,停止,開始錄製)

ios20-錄製音訊(播放,停止,開始錄製)

1,

//

//  ios20_audioRecordAppDelegate.h

//  ios20-audioRecord

//

//  Created by  on 13-6-10.

//  Copyright 2013 __MyCompanyName__. All rights reserved.

//

#import <UIKit/UIKit.h>

@interface ios20_audioRecordAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@end


//

//  ios20_audioRecordAppDelegate.m

//  ios20-audioRecord

//

//  Created by  on 13-6-10.

//  Copyright 2013 __MyCompanyName__. All rights reserved.

//

#import "ios20_audioRecordAppDelegate.h"

#import "audioRecord.h"

@implementation ios20_audioRecordAppDelegate

@synthesize window = _window;

- (BOOL)application:(UIApplication

*)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

self.window = [[UIWindowalloc] initWithFrame:[[UIScreenmainScreen] bounds]];

// Override point for customization after application launch.

audioRecord *audio=[[audioRecordalloc]init];

self.window.rootViewController=audio;

self

.window.backgroundColor = [UIColorwhiteColor];

    [self.windowmakeKeyAndVisible];

returnYES;

}

- (void)applicationWillResignActive:(UIApplication *)application

{

    /*

     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.

     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.

     */

}

- (void)applicationDidEnterBackground:(UIApplication *)application

{

    /*

     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 

     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

     */

}

- (void)applicationWillEnterForeground:(UIApplication *)application

{

    /*

     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.

     */

}

- (void)applicationDidBecomeActive:(UIApplication *)application

{

    /*

     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

     */

}

- (void)applicationWillTerminate:(UIApplication *)application

{

    /*

     Called when the application is about to terminate.

     Save data if appropriate.

     See also applicationDidEnterBackground:.

     */

}

@end

2.

//

//  audioRecord.h

//  ios20-audioRecord

//

//  Created by  on 13-6-10.

//  Copyright 2013 __MyCompanyName__. All rights reserved.

//

#import <UIKit/UIKit.h>

#import <AVFoundation/AVFoundation.h>

@interface audioRecord : UIViewController

{

    UILabel *label;

//定義專門進行錄製的類AVAudioRecoder

AVAudioRecorder *recoder;

    //播放

    AVAudioPlayer *player;

}

@property(nonatomic,retain) AVAudioRecorder *recoder;

@property(nonatomic,retain) AVAudioPlayer *player;

@end


//

//  audioRecord.m

//  ios20-audioRecord

//

//  Created by  on 13-6-10.

//  Copyright 2013 __MyCompanyName__. All rights reserved.

//

#import "audioRecord.h"

@implementation audioRecord

@synthesize recoder,player;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

{

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];

    if (self) {

// Custom initialization

    }

returnself;

}

- (void)didReceiveMemoryWarning

{

// Releases the view if it doesn't have a superview.

    [superdidReceiveMemoryWarning];

// Release any cached data, images, etc that aren't in use.

}

-(void)loadView{

UIView *view=[[UIViewalloc]initWithFrame:[UIScreenmainScreen].applicationFrame];

    view.backgroundColor=[UIColororangeColor];

    self.view=view;

label=[[UILabelalloc]initWithFrame:CGRectMake(90, 40, 160, 40)];

label.text=@"等待錄製聲音";

    [self.view addSubview:label];

UIButton *button=[UIButtonbuttonWithType:UIButtonTypeRoundedRect];

    button.frame=CGRectMake(90, 100, 100, 40);

    [button setTitle:@"開始錄製" forState:UIControlStateNormal];

    [button addTarget:selfaction:@selector(startPlayer) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:button];

UIButton *button2=[UIButtonbuttonWithType:UIButtonTypeRoundedRect];

    button2.frame=CGRectMake(90, 160, 100, 40);

    [button2 setTitle:@"停止錄製" forState:UIControlStateNormal];

    [button2 addTarget:selfaction:@selector(stopPlayer) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:button2];

UIButton *button3=[UIButtonbuttonWithType:UIButtonTypeRoundedRect];

    button3.frame=CGRectMake(90, 220, 100, 40);

    [button3 setTitle:@"播放錄製" forState:UIControlStateNormal];

    [button3 addTarget:selfaction:@selector(startRecord) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:button3];

}

-(void)startPlayer{

//設定label狀態顯示顯示為正在錄製

label.textColor = [UIColorredColor];

    label.text = @"錄製中...";

label.textAlignment = UITextAlignmentCenter;

//判斷當前的錄製狀態和播放狀態

if (recoder.isRecording) {

        [recoder stop];

    }

    if (player.isPlaying) {

        [player stop];

    }

    NSError *err = nil;

//設定錄製資訊

    [[AVAudioSessionsharedInstance] setCategory:AVAudioSessionCategoryRecorderror:&err];

    [[AVAudioSessionsharedInstance] setActive:YESerror:&err];

//設定取樣的詳細資料

NSMutableDictionary *settings = [NSMutableDictionarydictionary];

    [settings setValue:[NSNumbernumberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];

    [settings setValue:[NSNumbernumberWithFloat:44100.0] forKey:AVSampleRateKey]; //取樣率

    [settings setValue:[NSNumbernumberWithInt:1]

forKey:AVNumberOfChannelsKey];//通道的數目

    [settings setValue:[NSNumbernumberWithInt:16] forKey:AVLinearPCMBitDepthKey];//取樣位數預設 16

    [settings setValue:[NSNumbernumberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];//大端還是小端是記憶體的組織方式

    [settings setValue:[NSNumbernumberWithBool:NO] forKey:AVLinearPCMIsFloatKey];//取樣訊號是整數還是浮點數

//定義路徑,設定要儲存的位置  /BDEIDJDFDSF-SDfDS4232/document

NSString *dir = [NSHomeDirectory() stringByAppendingPathComponent:@"documents"];

//設定路徑

    NSString *savePath = [NSString stringWithFormat:@"%@/testAudio.aif",dir];

    NSLog(@"savaPath:%@",savePath);

//定義URL

    NSURL *fileUrl = [NSURL fileURLWithPath:savePath];

    if (err) {

NSLog(@"錄製之前配置出錯了!");

        return;

    }

//初始化了錄製的類

    recoder  = [[AVAudioRecorder alloc] initWithURL:fileUrl settings:settings error:&err];

//開始錄製

    [recoder record];

}

-(void)stopPlayer{

//設定label狀態顯示顯示為正在錄製

label.textColor = [UIColorgreenColor];

    label.text = @"已停止...";

label.textAlignment = UITextAlignmentCenter;

//正在錄製的時候,要停止錄製,正在播放的時候,要停止播放

if (recoder.isRecording) {

        [recoder stop];

    }

if(player.isPlaying){

        [player stop];

    }

}

-(void)startRecord{

//設定label狀態顯示顯示為正在錄製

label.textColor = [UIColorpurpleColor];

label.text = @"正在播放...";

label.textAlignment = UITextAlignmentCenter;

    NSError *err = nil;

//獲得錄製的檔案的路徑

//定義路徑,設定要儲存的位置  /BDEIDJDFDSF-SDfDS4232/document

NSString *dir = [NSHomeDirectory() stringByAppendingPathComponent:@"documents"];

//設定路徑

    NSString *savePath = [NSString stringWithFormat:@"%@/testAudio.aif",dir];

//定義URL

    NSURL *fileUrl = [NSURL fileURLWithPath:savePath];

//設定後臺播放

    [[AVAudioSessionsharedInstance] setCategory:AVAudioSessionCategoryPlaybackerror:&err];

//設定為啟用狀態

    [[AVAudioSessionsharedInstance] setActive:YESerror:&err];

//使用播放器進行播放

player  = [[AVAudioPlayeralloc] initWithContentsOfURL:fileUrl error:&err];

    [player play];

}

#pragma mark - View lifecycle

/*

// Implement loadView to create a view hierarchy programmatically, without using a nib.

- (void)loadView

{

}

*/

/*

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

- (void)viewDidLoad

{

    [super viewDidLoad];

}

*/

- (void)viewDidUnload

{

    [superviewDidUnload];

// Release any retained subviews of the main view.

// e.g. self.myOutlet = nil;

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

{

// Return YES for supported orientations

    return (interfaceOrientation == UIInterfaceOrientationPortrait);

}

@end