下载地址:点击打开链接
由于很简单,自写代码,我只写下代码。一看下就明白了。
//
// LCSound.h
// 英汉翻译
//
// Created by lichan on 14-1-3.
// Copyright (c) 2014年 lichan. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
@interface LCSound : NSObject<NSURLConnectionDataDelegate,AVAudioPlayerDelegate>
@property (strong,nonatomic)NSString *string;
@property (strong,nonatomic)NSMutableData *data;
- (void )soundData:(NSString *)str;
@end
//
// LCSound.m
// 英汉翻译
//
// Created by lichan on 14-1-3.
// Copyright (c) 2014年 lichan. All rights reserved.
//
#import "LCSound.h"
BOOL finished;
#import <AVFoundation/AVFoundation.h>
@implementation LCSound
- (void )soundData:(NSString *)str
{
NSString *speechString = [NSString stringWithFormat:@"http://translate.google.com/translate_tts?ie=UTF-8&oe=UTF-8&tl=zh&q=%@",str];
NSURL *url = [NSURL URLWithString:[speechString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2];
[NSURLConnection connectionWithRequest:request delegate:self];
}
- (void )soundData1:(NSString *)str
{
NSString *str1 =@"http://translate.google.com/translate_tts";
NSURL *postURL = [NSURL URLWithString:str1];
NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:postURL];
[postRequest setHTTPMethod:@"POST"];
NSString *param = [NSString stringWithFormat:@"?ie=UTF-8&oe=UTF-8&tl=zh&q=%@",str];
NSData *urlData = [param dataUsingEncoding:NSUTF8StringEncoding];
[postRequest setHTTPBody:urlData];
[NSURLConnection connectionWithRequest:postRequest delegate:self];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"%@",error);
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.data = [NSMutableData dataWithCapacity:10];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.data appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"%d",self.data.length);
AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithData:self.data error:nil];
player.delegate = self;
[player play];
}
@end