AVSpeechSynthesizer特殊字符

时间:2013-11-19 16:28:34

标签: ios emoji avspeechsynthesizer

我正在使用AVSpeechSynthesizer来读取字符串,但如果字符串有任何特殊字符(如表情符号微笑),则会出错。

如何为特殊字符添加字符串但是支持日语,中文?

2 个答案:

答案 0 :(得分:1)

使用NSString方法stringByTrimmingCharactersInSet和NSCharacterSet字母数字的反向集,这将过滤掉表情符号

因此,如果包含表情符号和中文字符的字符串被称为“textWithEmoji”,那么

NSString *textToSpeak = [textWithEmoji stringByTrimmingCharactersInSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet]];

'textToSpeak'将是相同的文字,但没有表情符号,其他没有字母数字字符

答案 1 :(得分:1)

试试这个。用空格放置表情符号字符串。

注意:如果您需要突出显示UITextView等文字,请不要删除表情符号字符串,因为 - (void)speechSynthesizer:willSpeakRangeOfSpeechString:utterance:delegate方法会得到错误的范围。

NSMutableString *string = [NSMutableString string];
NSString *text = @"Text with emoji.";    

[text enumerateSubstringsInRange:NSMakeRange(0, text.length)
                             options:NSStringEnumerationByComposedCharacterSequences
                          usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                              if ([substring isEmojiString]) {
                                  // If you need highlight text,replace the emoji with white space
                                  for (int i=0; i<substring.length; i++) {
                                      [string appendString:@" "];
                                  }
                              } else {
                                  [string appendString:substring];
                              }
                          }];

NSString类别

- (BOOL)isEmojiString {

BOOL returnValue = NO;
const unichar hs = [self characterAtIndex:0];
// surrogate pair
if (0xd800 <= hs && hs <= 0xdbff) {
    if (self.length > 1) {
        const unichar ls = [self characterAtIndex:1];
        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
        if (0x1d000 <= uc && uc <= 0x1f77f) {
            returnValue = YES;
        }
    }
} else if (self.length > 1) {
    const unichar ls = [self characterAtIndex:1];
    if (ls == 0x20e3) {
        returnValue = YES;
    }

} else {
    // non surrogate
    if (0x2100 <= hs && hs <= 0x27ff) {
        returnValue = YES;
    } else if (0x2B05 <= hs && hs <= 0x2b07) {
        returnValue = YES;
    } else if (0x2934 <= hs && hs <= 0x2935) {
        returnValue = YES;
    } else if (0x3297 <= hs && hs <= 0x3299) {
        returnValue = YES;
    } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
        returnValue = YES;
    }
}

return returnValue;

}