Mac OS X一直都有一個NSSpeechSynthesizer類,使用這個類可以很方便地在Cocoa應用程序中添加“文本到語音”功能。開發者可使用AV Foundation中的AVSpeechSynthesizer類向iOS應用程序中添加類似功能。這個類用來播放一個或多個語音內容,這些語音內容都是名為AVSpeechUtterance的類的實例。如果你希望播放語句“我愛你",具體的實現代碼如下所示:
AVSpeechSynthesizer *synthersizer = [[AVSpeechSynthesizer alloc] init];
AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:@"我愛你";];
?utterance.voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];
[synthersizer speakUtterance:utterance];
如果運行這段代碼,將聽見以中文讀出語句“我愛你”。現在通過創建一個簡單的應用程序實現這個功能,在應用程序中將用到AV Foundation會話。
代碼清單:
RGSpeechController.h
#import <AVFoundation/AVFoundation.h>
@interface RGSpeechController : NSObject
@property (strong, nonatomic, readonly) AVSpeechSynthesizer *synthesizer;
+ (instancetype)speechController;
- (void)beginConversation;
@end
RGSpeechController.m
#import "RGSpeechController.h"
@interface RGSpeechController ()
@property (strong, nonatomic) AVSpeechSynthesizer *synthesizer; // 1
@property (strong, nonatomic) NSArray *voices;
@property (strong, nonatomic) NSArray *speechStrings;
@end
@implementation RGSpeechController
+ (instancetype)speechController {
return [[self alloc] init];
}
- (instancetype)init {
self = [super init];
if (self) {
_synthesizer = [[AVSpeechSynthesizer alloc] init]; // 2
_voices = @[[AVSpeechSynthesisVoice voiceWithLanguage:@"en-US"], // 3
[AVSpeechSynthesisVoice voiceWithLanguage:@"en-GB"],
];
_speechStrings = [self buildSpeechStrings];
NSArray *speechVoices = [AVSpeechSynthesisVoice speechVoices];
for (AVSpeechSynthesisVoice *voice in speechVoices) {
NSLog(@"%@", voice.name);
}
}
return self;
}
- (NSArray *)buildSpeechStrings { ? ?// 4
return @[@"Hello AV Foundation. How are you?",
@"I'm well! Thanks for asking",
@"Are you excited about the book?",
@"Very! I have always felt so misunderstood",
@"What's your favorite feature",
@"Oh, they're all my babies. I couldn't possibly choose.",
@"It was great to speak with you!",
@"The pleasure was all mine! Have fun!"];
}
- (void)beginConversation {
for (NSUInteger i = 0; i < self.speechStrings.count; i++) {
AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:self.speechStrings[i]];
utterance.voice = self.voices[i % 2];
utterance.rate = 0.4f;// 播放語音內容的速率 0.0~1.0之間
utterance.pitchMultiplier = 0.8f;//在播放特定語句時改變聲音的音調 0.5(低音調)~2.0(高音調)之間
utterance.postUtteranceDelay = 0.1f;//在播放下一語句之前有短時間的暫停
[self.synthesizer speakUtterance:utterance];
}
}
@end
1、在類的擴展部分定義類所需的屬性,重新對之前在頭部定義的synthesizer屬性進行定義,這樣就可以支持讀寫操作。此外,還需要為具體對話中用到的聲音和語音字符串定義屬性。
2、創建一個新的AVSpeechSynthesizer的實例。該對象用于執行具體的“文本到語音”會話。對于一個或多個AVSpeechUtterance實例,該對象起到隊列的作用,提供了接口供控制和監視正在進行的語音播放。
3、創建一個包含兩個AVSpeechSynthesisVoice實例的NSArray對象。對于聲音的支持目前非常有限。開發者不能像在Mac機器上那樣使用指定名稱的語音進行播報。取而代之的是每種語言/區域設置都有預先設置好的聲音。這種情況下,1號揚聲器使用的是美式英語,2號揚聲器使用的是英式英語的發音。開發者可能通過調用AVSpeechSynthesisVoice中的speechVoices類方法來查看完整的聲音支持列表。
4、創建一個字符串數組用來定義所設計會話的有關前進和后退的處理。