iOS开发之语音说话

iOS开发之语音说话

在开发中遇到一个要写语音说话的功能 。  其效果类似于QQ语音说话。

因为语音说话的手势较多  因此我写了一个单例

第一步:
//语音说话要加入一个系统的第三方库AVFoundation.framework
代码如下
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
SingleManger.h文件里
#import SingleManger
 
  
@interface SingleManger : NSObject <AVAudioPlayerDelegate>
 
  
@property (nonatomic,strong)AVAudioPlayer *player;//播放器
@property (nonatomic,strong)AVAudioRecorder *recorder;//录音器
@property (nonatomic, strong) NSURL *frecordedFile;//保存语音地址

//单例入口
+(SingleManger *)sharedInstance;

//录音开始
- (void)recordStart; //:(NSString *)userid target:(id)target;

//取消录音
- (void)recordCancal;

//停止录音
- (void)recordStop;

//播放语音
- (void)recordPlay;

//存储语音
- (void)setRecorder;

@end



在.m里

//
//  SingleManger.m
//  SoundRecorder
//
//  Created by mi jibao on 15/4/26.
//  Copyright (c) 2015年 ETSU. All rights reserved.
//

#import "SingleManger.h"

@interface  SingleManger()

@end

static SingleManger *_singleManger;

@implementation SingleManger

//单例方法
+(SingleManger *)sharedInstance{

    @synchronized(self){
    
        if (_singleManger == nil) {
            _singleManger = [[SingleManger alloc]init];
        }
    }
    return _singleManger;
}

- (id)init{

    self = [super init];
    if (self) {
    }
    return self;
}
//设置语音保存路径
- (void)setRecorder{
    self.frecordedFile = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:@"RecordedFile"]];
    AVAudioSession *session = [AVAudioSession sharedInstance];
    NSError *sessionError;
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
    if(session == nil)
        NSLog(@"Error creating session: %@", [sessionError description]);
    else
        [session setActive:YES error:nil];
}
//录音开始
- (void)recordStart{
    //判断路径是否为空
    if (self.frecordedFile == nil) {
        [self setRecorder];
    }
    //初始化录音器
    self.recorder = [[AVAudioRecorder alloc]initWithURL:self.frecordedFile settings:nil error:nil];
    [self.recorder prepareToRecord];
    [self.recorder record];//录音
}
//取消录音
- (void)recordCancal{
    //获取文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //删除当前路径下得文件
    [fileManager removeItemAtURL:self.frecordedFile error:nil];
    self.frecordedFile = nil;
    self.recorder = nil;
}
//停止录音
- (void)recordStop{
    if (self.recorder != nil) {
        [self.recorder stop];
    }
}
//播放语音
- (void)recordPlay{
    NSError *playerError;
    //初始化播放器并且通过路径获取需要播放的音频
    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:self.frecordedFile error:&playerError];
    
    if (self.player == nil)
    {
        NSLog(@"ERror creating player: %@", [playerError description]);
        return;
    }
    //设置播放器的代理
    self.player.delegate = self;
    //播放
    [self.player play];
}
//音频播放结束回调方法
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)fla{

    NSLog(@"audioPlayerDidFinishPlaying");
}
@end





你可能感兴趣的:(ios,ios开发)