2014-02-20 86 views
1

我正在開發一個小應用程序,在這個應用程序中,必須有一個聲音說一些話。在應用程序中使用聲音

我可以使用某些程序使用的語音,如「Google翻譯」,「Vozme」或類似語言嗎?如果沒有,我該怎麼做?

+2

https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVSpeechSynthesizer_Ref/Reference/Reference.html – Kevin

+0

[如何以編程方式使用iOS語音合成器? (text to speech)](http://stackoverflow.com/questions/9939589/how-to-programmatically-use-ios-voice-synthesizers-text-to-speech) – MZimmerman6

回答

2

AVSpeechSynthesizer Class Reference可從iOS7獲取。文檔非常好。請務必將AVFoundation框架鏈接到您的項目。

這裏是一個工作的例子,講文本從的UITextField進入時的UIButton被點擊 - (假設名爲YOURViewController一個UIViewController子類)中的.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 

and in .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 
+0

這太好了。我不知道這是一件事。 +1給我一些知識。 – Forrest

+0

謝謝!我要去測試它。 這是一個很好的解決方案,但是,如果設備沒有iOS7會發生什麼?我需要一個「多」iOS版本。 –

+1

很好的回答!回去之前iOs7你必須去第三方,有OpenEars http://www.politepix.com/openears/或有iSpeech https://www.ispeech.org/developers – Jef

相關問題