我正在开发一个小应用程序,在这个应用程序中,必须有一个说一些话的声音。
我可以使用某些程序使用的语音,如“Google翻译”,“Vozme”或类似名称吗?如果没有,我该怎么做?
答案 0 :(得分:2)
AVSpeechSynthesizer Class Reference。文档非常好。请务必将 AVFoundation 框架与您的项目相关联。
这是一个工作示例,当点击 UIButton 时,会说出从 UITextField 输入的文字 - (假设一个名为YOURViewController的UIViewController子类)
in .h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface YOURViewController : UIViewController <AVSpeechSynthesizerDelegate, UITextFieldDelegate> {
IBOutlet UITextField *textFieldInput;// connect to a UITextField in IB
}
- (IBAction)speakTheText:(id)sender;// connect to a UIButton in IB
@end
和.m
#import "YOURViewController.h"
@interface YOURViewController ()
@end
@implementation YOURViewController
- (IBAction)speakTheText:(id)sender {
// create string of text to talk
NSString *talkText = textFieldInput.text;
// convert string
AVSpeechUtterance *speechUtterance = [self convertTextToSpeak:talkText];
// speak it...!
[self speak:speechUtterance];
}
- (void)viewDidLoad {
[super viewDidLoad];
}
- (AVSpeechUtterance*)convertTextToSpeak:(NSString*)textToSpeak {
AVSpeechUtterance *speechUtterance = [[AVSpeechUtterance alloc] initWithString:textToSpeak];
speechUtterance.rate = 0.2; // default = 0.5 ; min = 0.0 ; max = 1.0
speechUtterance.pitchMultiplier = 1.0; // default = 1.0 ; range of 0.5 - 2.0
speechUtterance.voice = [self customiseVoice];
return speechUtterance;
}
- (AVSpeechSynthesisVoice*)customiseVoice {
NSArray *arrayVoices = [AVSpeechSynthesisVoice speechVoices];
NSUInteger numVoices = [arrayVoices count];
AVSpeechSynthesisVoice *voice = nil;
for (int k = 0; k < numVoices; k++) {
AVSpeechSynthesisVoice *availCustomVoice = [arrayVoices objectAtIndex:k];
if ([availCustomVoice.language isEqual: @"en-GB"]) {
voice = [arrayVoices objectAtIndex:k];
}
// This logs the codes for different nationality voices available
// Note that the index that they appear differs from 32bit and 64bit architectures
NSLog(@"#%d %@", k, availCustomVoice.language);
}
return voice;
}
- (void)speak:(AVSpeechUtterance*)speechUtterance {
AVSpeechSynthesizer *speechSynthesizer = [[AVSpeechSynthesizer alloc] init];
speechSynthesizer.delegate = self;// all methods are optional
[speechSynthesizer speakUtterance:speechUtterance];
}
@end