iOS猿媛圈iOS DeveloperiOS

iOS录音和播放

2016-06-06  本文已影响6201人  FlyElephant

现在的社交应用中录音和播放时必不可少的一部分,当然有些为了互动性更强也会加入一些声音,关于录音的博客网上也是不胜其数,当然效果也是差强人意,要么是到处转载,要么就是下载之后发现不能录音或者不能播放,如果你想做一些些简单的录音和播放,可以参考本文,先来看一下效果图:

FlyElephant.png

录音

AVAudioRecorder是录音必须要用的,其次就是要设置录音的路径,存放在本地,之后的播放或者说上传都通过此路劲进行进行操作,简单看一下核心代码:
<pre><code>`

NSLog(@"FlyElephant-startRecording");;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryRecord error:nil];

NSError *error = nil;
self.audioRecorder = [[ AVAudioRecorder alloc] initWithURL:self.recordUrl settings:[self audioRecordingSettings] error:&error];
self.audioRecorder.meteringEnabled = YES;
if ([self.audioRecorder prepareToRecord] == YES){
    self.audioRecorder.meteringEnabled = YES;
    [self.audioRecorder record];
}else {
    NSLog(@"FlyElephant--初始化录音失败");
}`</code></pre>

录音路径:

NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(
                                                        NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir = [dirPaths objectAtIndex:0];
NSString *soundFilePath = [docsDir
                           stringByAppendingPathComponent:@"recordTest.caf"];

NSURL *url = [NSURL fileURLWithPath:soundFilePath];
self.recordUrl=url;

录音设置:
<pre><code>`

录音播放

AVAudioPlayer是必不可少的,调用起来非常方便,设置循环次数,直接播放即可,当然也可以进行声音设置,根据实际需要个人设置即可:

NSLog(@"FlyElephant-playRecording");
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
NSError *error;
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:self.recordUrl error:&error];
self.audioPlayer.numberOfLoops = 0;
[self.audioPlayer play];
NSLog(@"FlyElephant-playing");

声音没法展示,看一下Log:
<pre><code>**2016-06-06 14:49:56.304 FEAudioRecord[2341:1257382] FlyElephant-startRecording** **2016-06-06 14:49:59.838 FEAudioRecord[2341:1257382] stopRecording** **2016-06-06 14:49:59.873 FEAudioRecord[2341:1257382] stopped** **2016-06-06 14:50:01.239 FEAudioRecord[2341:1257382] FlyElephant-playRecor**</code></pre>

上一篇 下一篇

猜你喜欢

热点阅读