【发布时间】:2014-02-20 15:09:24
【问题描述】:
我正在开发一个小应用程序,在这个应用程序中,必须有一个可以说一些话的声音。
我可以使用某些程序使用的语音,例如“Google Translate”、“Vozme”或类似的吗?如果没有,我该怎么做?
【问题讨论】:
我正在开发一个小应用程序,在这个应用程序中,必须有一个可以说一些话的声音。
我可以使用某些程序使用的语音,例如“Google Translate”、“Vozme”或类似的吗?如果没有,我该怎么做?
【问题讨论】:
AVSpeechSynthesizer Class Reference 在 iOS7 中可用。文档非常好。请务必将 AVFoundation 框架链接到您的项目。
这是一个工作示例,当轻按 UIButton 时,它会说出从 UITextField 输入的文本 - (假设 UIViewController 子类名为 YOURViewController)
在.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
【讨论】: