網頁

2012年6月4日 星期一

AVFoundation應用、Google_TTS

【環境:xCode4.3.2 , ios5.1】

說明:
以uitabBarController為基礎框架,自定義tabBar,我的tabBarItem用的是30x30的大小,且背景須為透明,顏色為淺色系。
使用uitextview、AVFoundation應用、Google_TTS。
其中tts的部份加入,中英文判斷。
應用到了一點QuartzCore去處理uitextview的外框。

值得注意的還有tts若想用其他語言發音
http://translate.google.com/translate_tts?tl=en&q=text
則更改紅字的部份,此部份為countryCode

故此範例須引用
#import <AVFoundation/AVFoundation.h> 
#import <QuartzCore/QuartzCore.h>
引用的protocol有以下兩個
<UITabBarDelegate,UITabBarControllerDelegate>
<UITextViewDelegate>

※若你的音效程式碼運行正確,但實機測試卻撥不出來,可以檢查<你iphone的震動的按鈕是否打開>。

※若simulation也無聲音,大概就必須檢查你的程式碼stop & pause部分代碼,是否和play搞混。


範例下載  若只需單純的tts 參考,此部份提供當初我網路上參考tts的程式






<以下部分程式碼範例-主要為textview應用和google tts的應用>
 
//
//  view2.m
//  sound & tts
//
//  Created by jhaoheng on 2012/6/1.
//  Copyright (c) 2012年 __n11_studio__. All rights reserved.
//

#import "view2.h"

//由於本範例有使用到 Layer 類別的方法,所以必須先匯入其對應的標頭檔和 Framework。
#import <QuartzCore/QuartzCore.h>

@implementation view2

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        //self.title = @"three";
        UIImage *img_speak = [UIImage imageNamed:@"google.png"];
        UITabBarItem *item3 = [[UITabBarItem alloc]initWithTitle:@"G_TTS" image:img_speak tag:1]; 
        self.tabBarItem = item3;
        
        /*
        The item’s image. If nil, an image is not displayed.
        
        The images displayed on the tab bar are derived from this image. If this image is too large to fit on the tab bar, it is scaled to fit. The size of an tab bar image is typically 30 x 30 points. The alpha values in the source image are used to create the unselected and selected images—opaque values are ignored.
        */
        /*
         if you want to create icons for iPhone UITabBar ,you can read this website
         http://steveweller.com/articles/toolbar-icons/
        */
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    input_text = [[UITextView alloc]initWithFrame:CGRectMake(10, 10, 300, 150)];
    input_text.font = [UIFont fontWithName:@"Arial" size:20];
    input_text.textColor = [UIColor whiteColor];
    input_text.delegate = self;
    input_text.backgroundColor = [UIColor whiteColor];
    input_text.text = @"you can type something in this frame and click the speaker button to pronounce";
    input_text.returnKeyType = UIReturnKeyDefault;
    input_text.keyboardType = UIKeyboardTypeDefault;
    /*
     autocapitalizationType — 首字大寫
     autocorrectionType — 自動更正錯字
     enablesReturnKeyAutomatically — 確認使用者有輸入文字後才啟用return鍵
     keyboardAppearance — 鍵盤外型
     keyboardType — 鍵盤種類
     returnKeyType — return鍵的類型
     secureTextEntry — 隱藏輸入的文字
    */
    //設定是否可捲動
    input_text.scrollEnabled = YES;
    //自適應高度
    //text.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    
    //設定橘色背景與棕色邊框
    [input_text setBackgroundColor:[UIColor orangeColor]];
    [[input_text layer] setBorderColor:[[UIColor brownColor] CGColor]];
    //邊框粗細
    [[input_text layer] setBorderWidth:1.5];
    //設定圓角程度
    [[input_text layer] setCornerRadius:20];
    /*指定內文字體大小並置中
    [text setFont:[UIFont boldSystemFontOfSize:50.0]];
    [text setTextAlignment:UITextAlignmentCenter];
    */
    //設定無法再被編輯
    [input_text setEditable:YES];
     
    //使內文保持在UITextView邊框之內
    [input_text setClipsToBounds: YES];
    [self.view addSubview:input_text];
    
    UIButton *speaker = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [speaker setTitle:@"speaker" forState:UIControlStateNormal];
    [speaker setTitle:@"connect" forState:UIControlStateHighlighted];
    speaker.frame = CGRectMake(20, 295, 280, 40);
    [speaker addTarget:self action:@selector(machine_speak) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:speaker];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -uibutton
-(void)machine_speak
{
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"file.mp3"];
    NSString *urlString;
    if ([input_text.text canBeConvertedToEncoding: NSASCIIStringEncoding]) {//如果是英語
        urlString = [NSString stringWithFormat:@"http://www.translate.google.com/translate_tts?tl=en&q=%@",input_text.text];
    }  
    else { //如果是非英語 
        urlString = [NSString stringWithFormat:@"http://www.translate.google.com/translate_tts?tl=zh-TW&q=%@",input_text.text];
    } 
    NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
    [request setValue:@"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:2.0.1) Gecko/20100101 Firefox/4.0.1" forHTTPHeaderField:@"User-Agent"];
    NSURLResponse* response = nil;
    NSError* error = nil;
    NSData* data = [NSURLConnection sendSynchronousRequest:request
                                         returningResponse:&response
                                                     error:&error];
    [data writeToFile:path atomically:YES];
    
    NSError *err;
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) 
    {    
        player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&err];
        player.volume = 0.8f;
        [player prepareToPlay];
        [player setNumberOfLoops:0];
        [player play];    
    }
     
}

#pragma mark - UITextView Delegate Methods     

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)closetext
{    
    if ([closetext isEqualToString:@"\n"]) {    
        
        [input_text resignFirstResponder];    
        
        return NO;    
        
    }
    return YES;    
}

@end
 

沒有留言:

張貼留言