ios20-录制音频(播放,停止,开始录制)

来源:互联网 发布:mac口红russian red 编辑:程序博客网 时间:2024/04/26 17:51

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];

   return YES;

}


- (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

    }

   return self;

}


- (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.viewaddSubview:label];

   UIButton *button=[UIButtonbuttonWithType:UIButtonTypeRoundedRect];

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

    [buttonsetTitle:@"开始录制" forState:UIControlStateNormal];

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

    [self.viewaddSubview:button];

   UIButton *button2=[UIButtonbuttonWithType:UIButtonTypeRoundedRect];

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

    [button2setTitle:@"停止录制" forState:UIControlStateNormal];

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

    [self.viewaddSubview:button2];

   UIButton *button3=[UIButtonbuttonWithType:UIButtonTypeRoundedRect];

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

    [button3setTitle:@"播放录制" forState:UIControlStateNormal];

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

    [self.viewaddSubview:button3];

    

}

-(void)startPlayer{

    //设置label状态显示显示为正在录制

   label.textColor = [UIColorredColor];

    label.text = @"录制中...";

   label.textAlignment =UITextAlignmentCenter;

    

    //判断当前的录制状态和播放状态

   if (recoder.isRecording) {

        [recoderstop];

    }

    if (player.isPlaying) {

        [playerstop];

    }

    NSError *err = nil;

   //设定录制信息

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

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

    //设置采样的详细数据

   NSMutableDictionary *settings = [NSMutableDictionarydictionary];

    [settingssetValue:[NSNumbernumberWithInt:kAudioFormatLinearPCM]forKey:AVFormatIDKey];

    [settingssetValue:[NSNumbernumberWithFloat:44100.0]forKey:AVSampleRateKey];//采样率

    [settingssetValue:[NSNumbernumberWithInt:1]

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

    [settingssetValue:[NSNumbernumberWithInt:16]forKey:AVLinearPCMBitDepthKey];//采样位数默认 16

    [settingssetValue:[NSNumbernumberWithBool:NO]forKey:AVLinearPCMIsBigEndianKey];//大端还是小端是内存的组织方式

    [settingssetValue:[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];

   //开始录制

    [recoderrecord];


}

-(void)stopPlayer{

    //设置label状态显示显示为正在录制

   label.textColor = [UIColorgreenColor];

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

   label.textAlignment =UITextAlignmentCenter;

    

    //正在录制的时候,要停止录制,正在播放的时候,要停止播放

   if (recoder.isRecording) {

        [recoderstop];

    }

    

   if(player.isPlaying){

        

        [playerstop];

    }

}

-(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:fileUrlerror:&err];

    

    [playerplay];

    

}


#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


原创粉丝点击