標籤:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//建立語音配置,appid必須要傳入,僅執行一次則可
NSString *initString = [[NSString alloc] initWithFormat:@"appid=570f3db3"];
//所有服務啟動前,需要確保執行createUtility
[IFlySpeechUtility createUtility:initString];
return YES;
}
製作錄音檔案,使用apple原生API架構。需要添加標頭檔AVFoundation架構,在程式第一次啟用時候會請求是否開啟此項功能。另使用科大API只能免費使用線上SDK,調用離線SDK只能用於3個iOS裝置使用35天。離線購買價格很貴。
#import "iflyMSC/IFlyMSC.h"
#import "iflyMSC/IFlySpeechConstant.h"
#import "iflyMSC/IFlySpeechRecognizerDelegate.h"
#import "iflyMSC/IFlySpeechRecognizer.h"
@import AVFoundation;
<AVAudioRecorderDelegate>使用代理
@property (nonatomic,strong)IFlySpeechRecognizer *iFlySpeechRecognizer;
@property (nonatomic,strong)AVAudioRecorder *recorder;
@property (nonatomic,strong)AVAudioPlayer *player;
@property (nonatomic,strong)NSTimer *timer;
@property (nonatomic,strong)NSURL *url;
@property (nonatomic,strong)NSMutableDictionary *dict;
@property (nonatomic,strong)UIProgressView *gress;
@property (nonatomic,strong)NSMutableString *text;
@property (weak, nonatomic) IBOutlet UITextField *textField;
AVAudioSession *session = [AVAudioSession sharedInstance];
//單例模式,設定為錄音並播放
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
[session setActive:YES error:nil];
NSString *str = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
self.url = [NSURL fileURLWithPath:[str stringByAppendingPathComponent:@"myFirstRecord.caf"]];
設定檔案的儲存路徑
self.gress = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
self.gress.progress = 0;設定進度條
self.gress.frame = CGRectMake(90, 200, 200, 2);
[self.view addSubview:self.gress];
self.dict = [NSMutableDictionary dictionary];
[self.dict setObject:@(kAudioFormatLinearPCM) forKey:AVFormatIDKey];
[self.dict setObject:@10000 forKey:AVSampleRateKey];
[self.dict setObject:@1 forKey:AVNumberOfChannelsKey];
[self.dict setObject:@8 forKey:AVLinearPCMBitDepthKey];
[self.dict setObject:@(YES) forKey:AVLinearPCMIsFloatKey];
if (!_recorder) {
_recorder = [[AVAudioRecorder alloc]initWithURL:self.url settings:self.dict error:nil];
_recorder.delegate = self;
_recorder.meteringEnabled = YES;
}
if (!_player) {
_player = [[AVAudioPlayer alloc]initWithContentsOfURL:self.url error:nil];
}
[self start];
- (void)start{
_iFlySpeechRecognizer = [IFlySpeechRecognizer sharedInstance]; //設定聽寫模式
_iFlySpeechRecognizer.delegate = self;
//2.設定聽寫參數
[_iFlySpeechRecognizer setParameter: @"iat" forKey: [IFlySpeechConstant IFLY_DOMAIN]];
//asr_audio_path是錄音檔案名稱,設定value為nil或者為空白取消儲存,預設儲存目錄在 Library/cache下。
[_iFlySpeechRecognizer setParameter:@"asrview.pcm" forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];
//3.啟動識別服務 [_iFlySpeechRecognizer start];
}
- (NSTimer *)timer{
if (!_timer) {
_timer = [NSTimer scheduledTimerWithTimeInterval:1/20.0 target:self selector:@selector(showProgress:) userInfo:nil repeats:YES];
NSLog(@"nstime");
}
return _timer;
}
- (void)showProgress:(NSTimer*)t{
[self.recorder updateMeters];
float power = [self.recorder averagePowerForChannel:0];//取得第一個通道的音頻,注意音頻強度範圍時-160到0
self.gress.progress = (power+160)/160.0;
}
- (IBAction)recording:(id)sender {
if (![self.recorder isRecording]) {
[self.recorder record];
self.timer.fireDate = [NSDate distantPast];
}
NSLog(@"錄音開始!");
}
- (IBAction)pause:(id)sender {
if (![self.recorder isRecording]) {
[self.recorder pause];
self.timer.fireDate = [NSDate distantFuture];
}else{
[self.recorder record];
self.timer.fireDate = [NSDate distantPast];
}
NSLog(@"暫停切換!");
}
- (IBAction)stop:(id)sender {
[self.recorder stop];
NSLog(@"錄音結束!");
self.timer.fireDate = [NSDate distantFuture];
self.timer = nil;
self.gress.progress = 0;
}
- (IBAction)iflyClick:(id)sender {
NSLog(@"iflyClick");按下button的時候調用方法TouchDown
_text = [[NSMutableString alloc]init];
[_iFlySpeechRecognizer startListening];
}
- (IBAction)iflyClickstop:(id)sender {
NSLog(@"iflyClickstop");離開button後調用的方法,無論是在按鈕上離開還是在按鈕外離開都執行。TouchUpInside&TouchUpOutside
[_iFlySpeechRecognizer stopListening];
}
#pragma - mark - AVAudioRecordDelegate
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:nil]; //開啟擴音器
[session setActive:YES error:nil];
if(![self.player isPlaying]){
[self.player play];
}
NSLog(@"錄音完成!");
}
#pragma - mark - IFlySpeechRecognizerDelegate
- (void) onError:(IFlySpeechError *) errorCode{
NSLog(@"onError-----------------%@",errorCode);
}
- (void) onResults:(NSArray *) results isLast:(BOOL)isLast{
NSLog(@"onResults-----------------%@",results);
NSMutableString *result = [[NSMutableString alloc] init];
NSDictionary *dic = [results objectAtIndex:0];
for (NSString *key in dic){
[result appendFormat:@"%@",key];//合并結果
}
NSLog(@"result-------%@",result);
NSMutableArray *strArr = [[result componentsSeparatedByString:@"\"}]}"] mutableCopy];
[strArr removeLastObject];
for (NSString *str in strArr) {
[_text appendString:[[str componentsSeparatedByString:@"\""]lastObject]];
}
NSLog(@"_text-------%@",_text);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
self.textField.text = _text;
});
}
-(void)viewWillDisappear:(BOOL)animated
{
[_iFlySpeechRecognizer cancel];
_iFlySpeechRecognizer.delegate = nil;
//設定回非語義識別
[_iFlySpeechRecognizer destroy];
[super viewWillDisappear:animated];
}
iOS開發之語音功能實現