录音与播放

#import "ViewController.h"
//导入AVFoundation框架
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()
{
    NSURL *recordURL;
    AVAudioPlayer *player;
    AVAudioRecorder *recorder;
}
@end
@implementation ViewController
设置button状态为UIControlEventTouchDown开始录音
- (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];
}
设置button状态为UIControlEventTouchUpInside停止录音
- (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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值