AVSpeechSynthesizer说话,再次运行,开始前需要10秒左右

时间:2015-04-19 23:17:02

标签: ios objective-c iphone avspeechsynthesizer

当我运行此代码时,它运行正常,但是什么时候 我再次运行它,它运行大约需要10秒左右,有时也会被切断。

编辑:下面我添加了更多代码,以便更好地了解代码的执行位置。这种情况下的主要线程是实际的Siri UI。这是在越狱设备上执行的代码。它允许我用印地语用Siri回复我父母那些不太懂英语的父母......

- (BOOL)handleSpeech:(NSString *)text withTokens:(NSSet *)tokens withSession:(id<APSiriSession>)session {
  if ([tokens containsObject:@"siri"]) {
  NSRegularExpression *queryRegex = [NSRegularExpression regularExpressionWithPattern:@"(?:.*)Siri ?(.*)" options:NSRegularExpressionCaseInsensitive error:nil];
  NSArray *arrayOfAllMatches = [queryRegex matchesInString:text options:0 range:NSMakeRange(0, [text length])];

  NSString *query = nil;
  for (NSTextCheckingResult *match in arrayOfAllMatches) {
      if (match.numberOfRanges > 1) {
          query = [text substringWithRange:[match rangeAtIndex:1]];
      }
  }

  if (!query || query.length == 0) {
      query = @"";
  }
  [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
  AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  [manager.requestSerializer setTimeoutInterval:8.0];
  manager.responseSerializer = [AFHTTPResponseSerializer serializer];
  [manager GET:[NSString stringWithFormat:@"http://api.salmanburhan.com/Siri/Hindi/?input=%@", [query stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
      NSLog(@"JSON: %@", responseObject);

         NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
         AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:string];
         utterance.rate = 0.1000;
         utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"hi-IN"];
         AVSpeechSynthesizer *synthesizer = [[AVSpeechSynthesizer alloc] init];
        [synthesizer speakUtterance:utterance];
        //[synthesizer pauseSpeakingAtBoundary:AVSpeechBoundaryWord];


      [session sendTextSnippet:[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] temporary:NO scrollToTop:NO dialogPhase:@"Summary"];

  } failure:^(NSURLSessionDataTask *task, NSError *error) {
      NSLog(@"Error: %@", error);
      [session sendTextSnippet:[NSString stringWithFormat:@"An Error Occurred, Sorry.\n\n%@", error] temporary:NO scrollToTop:NO dialogPhase:@"Error"];
      [session sendRequestCompleted];
  }];

  return YES;
  }
return NO;
}

1 个答案:

答案 0 :(得分:0)

你是如何调用代码的?每当你在iOS中看到“需要n秒启动”时,你经常会遇到主线程问题。

所有UI工作必须在主线程上,所有“昂贵的”非UI工作不得在主线程上。这是我从http://www.raywenderlich.com/31166/25-ios-app-performance-tips-tricks#mainthread复制的代码片段 - 这是一篇很棒的博客,你应该阅读。

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // switch to a background thread and perform your expensive operation

    dispatch_async(dispatch_get_main_queue(), ^{
        // switch back to the main thread to update your UI

    });
});