Continuous conversion of text to speech from json data - iphone

I am designing an app that needs text to speech. I am using the library that is posted here to convert text to speech. I have to retrieve text from Json url, and pass the values to text to speech. I am able to retrieve Json data and convert it to text to speech for the ObjectatIndex 0 using the following code...
SBJSON *json = [[SBJSON alloc]init];
fliteEngine = [[FliteTTS alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.sampleurl.txt"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *jsonstring = [[NSString alloc]initWithData:response encoding:NSUTF8StringEncoding];
NSArray *asanasList = [json objectWithString:jsonstring error:nil];
NSArray *asanas =[asanasList objectForKey:#"yogagurubackpain"];
for(NSDictionary *test in asanas)
{
UrlValues *myasanas = [[UrlValues alloc]init];
myasanas.asanatitle = [test objectForKey:#"asanatitle"];
myasanas.asanatranscript = [test objectForKey:#"asanatranscript"];
myasanas.asanapicture = [test objectForKey:#"asanapicture"];
[data.yoga addObject:myasanas];
[myasanas release];
}
UrlValues *asana=[[data yoga]objectAtIndex:0];
self.AsanaName.text = [asana asanatitle];
self.AsanaTranscript.text = [asana asanatranscript];
NSString *imageUrl = [asana asanapicture];
NSString* mapUrl = [imageUrl stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSData* imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:mapUrl]];
UIImage* image = [[UIImage alloc] initWithData:imageData];
self.AsanaImage.image = image;
NSString *speak = self.AsanaTranscript.text;
[fliteEngine setVoice:#"cmu_us_rms"];
[fliteEngine speakText:speak];
[fliteEngine setPitch:100.0 variance:11.0 speed:0.4];
[imageData release];
[image release];
[jsonstring release];
[json release];
Now my problem is how can i go to the next object automatically after completion of the playing of first one. The process must continue for all the objects. The corresponding images etc must load on the page after the text to speech is done for the first one... Plz help me...

Looking at the source of the linked library, it looks like you'll have to hack a method into FliteTTS.m. If you look at the source, it's using an AVAudioPlayer to play back a generated WAV file. It's also setting itself as the audio player's delegate. If you implement the audioPlayerDidFinishPlaying:successfully: delegate method and play the next chunk when it's called, you should be able to have a semi-continuous text-to-speech stream.

Related

Parsing XML String From WebServer

Alright, so here's where I'm at with my app.
I've got some code that connects to a remote server and grabs some XML data, and forms it into a string. Here is the code below:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"GET"];
NSString *accept = [NSString stringWithFormat:#"application/xml"];
[request addValue:accept forHTTPHeaderField: #"Accept"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString* responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(#"%#",responseString);
Which returns
That's exactly the information I want. My question is how I can get the double value out of the gold brackets and into my application to use.
Thanks a lot!
There are a lot of tutorials of how to use NSXMLParser. For example, ray wenderlich or here and here.
There's quite a few XML parsing options available - ranging from libxml2, to NSXMLParser and a host of open-source projects.
One of my favorite XML parsers is RaptureXML, which can be installed via CocoaPods.
I like to create a category on RXMLElement to parse as follows:
- (PFCurrentConditions*)asCurrentCondition
{
NSString* summary = [[self child:#"weatherDesc"] text];
PFTemperature* temp = [PFTemperature temperatureWithFahrenheitString:[[self child:#"temp_F"] text]];
NSString* humidity = [[self child:#"humidity"] text];
NSString* wind =
[NSString stringWithFormat:#"Wind: %# km %#", [[self child:#"windspeedKmph"] text], [[self child:#"winddir16Point"] text]];
NSString* imageUri = [[self child:#"weatherIconUrl"] text];
return [PFCurrentConditions conditionsWithSummary:summary temperature:temp humidity:humidity wind:wind imageUrl:imageUri];
}
So, you can then use it as follows:
RXMLElement* rootElement = [RXMLElement elementFromXMLData:response.responseData];
__autoreleasing PFWeatherReport* weatherReport = [rootElement asWeatherReport];
Again, this is one of countless options, but my personal favorite.

From iphone app to face.com api: upload raw image

I just test the face.com face recognition api and I have success with json requests:
NSString *url = #"http://api.face.com/faces/detect.json?api_key=myapi&api_secret=mysecret&urls=http://userserve-ak.last.fm/serve/_/47363849/Christina+Aguilera+HQ+PNG.png";
// Create new SBJSON parser object
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
// Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON status objects
NSDictionary *obj = [parser objectWithString:json_string];
//
NSString *status = [obj objectForKey:#"status"];
//
NSLog(#"status: %#", status);
This works when I pass the api key, secret and the IMAGE ON THE WEB as GET params, like:
http://api.face.com/faces/detect.json?api_key=4b4b4c6d54c37&api_secret= &urls= http://farm3.static.flickr.com/2566/3896283279_0209be7a67.jpg
Now, I want to upload a raw image data from my app...but this is not so well documented on the site:
http://developers.face.com/docs/api/faces-detect/
There it says:
Code:
Optional [no name] The raw image data for the photo (when instead of url, an image is uploaded)
This is the problem:
How do I pass the raw data as POST along with the apikey and secret?
I know it must be as POST, but how?
Raw data = NSData, so all you need to do is append the imageData to the URL, as done below.
NSString *url = [NSString stringWithFormat:#"http://api.face.com/faces/detect.json?api_key=myapi&api_secret=mysecret&code=%#", imageData];

How to upload data from iphone app to mysql data base

I have a EMR app and i want that i may send the data which i have collected like images and voice to server. in data base so how can i do this . Is there any way to send these data to server through post method.
Here is an example of a HTTP Post request
// define your form fields here:
NSString *content = #"field1=42&field2=Hello";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://www.example.com/form.php"]];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:[content dataUsingEncoding:NSISOLatin1StringEncoding]];
// generates an autoreleased NSURLConnection
[NSURLConnection connectionWithRequest:request delegate:self];
Might want to reference http://developer.apple.com/library/ios/#documentation/cocoa/reference/foundation/Classes/NSURLConnection_Class/Reference/Reference.html
This tutorial is also helpful http://www.raywenderlich.com/2965/how-to-write-an-ios-app-that-uses-a-web-service
In that case, you can do follow two ways:
1. if you strictly like to using POST (i like), u can using cocoahttpserver project:
https://github.com/robbiehanson/CocoaHTTPServer
In iphone app, you can do this code to send POST request:
-(NSDictionary *) getJSONAnswerForFunctionVersionTwo:(NSString *)function
withJSONRequest:(NSMutableDictionary *)request;
{
[self updateUIwithMessage:#"server download is started" withObjectID:nil withLatestMessage:NO error:NO];
NSDictionary *finalResultAlloc = [[NSMutableDictionary alloc] init];
#autoreleasepool {
NSError *error = nil;
NSString *jsonStringForReturn = [request JSONStringWithOptions:JKSerializeOptionNone serializeUnsupportedClassesUsingBlock:nil error:&error];
if (error) NSLog(#"CLIENT CONTROLLER: json decoding error:%# in function:%#",[error localizedDescription],function);
NSData *bodyData = [jsonStringForReturn dataUsingEncoding:NSUTF8StringEncoding];
NSData *dataForBody = [[[NSData alloc] initWithData:bodyData] autorelease];
//NSLog(#"CLIENT CONTROLLER: string lenght is:%# bytes",[NSNumber numberWithUnsignedInteger:[dataForBody length]]);
NSString *functionString = [NSString stringWithFormat:#"/%#",function];
NSURL *urlForRequest = [NSURL URLWithString:functionString relativeToURL:mainServer];
NSMutableURLRequest *requestToServer = [NSMutableURLRequest requestWithURL:urlForRequest];
[requestToServer setHTTPMethod:#"POST"];
[requestToServer setHTTPBody:dataForBody];
[requestToServer setTimeoutInterval:600];
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[urlForRequest host]];
NSData *receivedResult = [NSURLConnection sendSynchronousRequest:requestToServer returningResponse:nil error:&error];
if (error) {
NSLog(#"CLIENT CONTROLLER: getJSON answer error download:%#",[error localizedDescription]);
[self updateUIwithMessage:[error localizedDescription] withObjectID:nil withLatestMessage:YES error:NO];
[finalResultAlloc release];
return nil;
}
NSString *answer = [[NSString alloc] initWithData:receivedResult encoding:NSUTF8StringEncoding];
JSONDecoder *jkitDecoder = [JSONDecoder decoder];
NSDictionary *finalResult = [jkitDecoder objectWithUTF8String:(const unsigned char *)[answer UTF8String] length:[answer length] error:&error];
[finalResultAlloc setValuesForKeysWithDictionary:finalResult];
[answer release];
[self updateUIwithMessage:#"server download is finished" withObjectID:nil withLatestMessage:NO error:NO];
if (error) NSLog(#"CLIENT CONTROLLER: getJSON answer failed to decode answer with error:%#",[error localizedDescription]);
}
NSDictionary *finalResultToReturn = [NSDictionary dictionaryWithDictionary:finalResultAlloc];
[finalResultAlloc release];
return finalResultToReturn;
}
Don't forget to pack attributes with images to base64.
Finally, if u don't like to keep data, which u send in you mac app, u can send to u database using any database C api. I recommend to using core data to save receive data.

reload a UIwebview from main view automatically (view based application)

I have a view based application. Now on the opening view I have some buttons and a picture and a small web view.
The web view has its own .h/.m file the calls a JSON request to fill it. That works great.
My problem is that when the app is closed and reopened the webview is not updating. How to I get that to work?
welcomeMessage.m (connected to webview)
- (void)awakeFromNib{
[NSThread sleepForTimeInterval:1];
NSUserDefaults *gMess =[NSUserDefaults standardUserDefaults];
NSString *myMess=[gMess stringForKey:#"welcomeMessage"];
NSLog(#"WEBVIEW CLASS %#",myMess);
if (myMess == NULL) {
NSString *html = [NSString stringWithFormat:#"<body style ='background-color:#FFFF33' align='center'><p>Welcome</p><p>Check out our Daily Winners</p></body>"];
[welcomeMessage loadHTMLString:html baseURL:[NSURL URLWithString:#"http://www.myapp.com/api/welcome/welcomemessage.php?iappid=37"]];
}
else{
NSString *html = [NSString stringWithFormat:#"<body style ='background-color:#FFFF33' align='center'> %# </body>", myMess];
[welcomeMessage loadHTMLString:html baseURL:[NSURL URLWithString:#"http://www.myapp.com/api/welcome/welcomemessage.php?iappid=37"]];
}
}
Mainviewcontroller json
- (void)viewDidLoad
{
// Create new SBJSON parser object
SBJsonParser *object = [[SBJsonParser alloc] init];
// Prepare URL request to download statuses from Twitter
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.kickintheapp.com/api/welcome/welcomemessage.php?iappid=37"]];
// NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://twitter.com/statuses/public_timeline.json"]];
// Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSError *jsonParseError;
NSDictionary *status = [object objectWithString:json_string error:&jsonParseError];
if (!status) {
// there's been a parse error; look at jsonParseError
// for example:
NSLog(#"JSON parse error: %#", jsonParseError);
}
NSString *messValue = [status objectForKey:#"message"];
NSUserDefaults *gMess = [NSUserDefaults standardUserDefaults];
[gMess setObject:messValue forKey:#"welcomeMessage"];
}
Check out Apple's documentation on an iOS's lifecycle. You will find all callbacks you need in there:
http://developer.apple.com/library/ios/#documentation/uikit/reference/UIApplicationDelegate_Protocol/Reference/Reference.html
Especially – applicationWillEnterForeground: will be interesting for you.

XML parsing text encoding problem

I need to parse a XML feed with french accent like 'é' .
When I parse the XML I lost the accents...
What's wrong in my code...
NSString *url = [NSString stringWithFormat:#"%#",#"my_xml_url"];
NSURL *myURL = [NSURL URLWithString:url];
NSString *myData = [[NSString alloc] initWithContentsOfURL:myURL];
XMLParser *parser = [[XMLParser alloc] init];
[parser parseXMLFile:myData];
And when I start parsing.....
- (void)parseXMLFile:(NSString *)data {
BOOL success;
//array for the ranking
rows = [[NSMutableArray alloc] init];
index = 0;
self.currentString = [NSMutableString string];
storingCharacters = NO;
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:[data data UsingEncoding:NSUTF8StringEncoding]];
[parser setDelegate:self];
[parser setShouldResolveExternalEntities:YES];
success = [parser parse];
self.currentString = nil;
//release memory
[parser release];
}
I can't see where is the problem...
Thanks
It appears to be an encoding issue with stringWithContentsOfURL
Try:
NSError *lookupError = nil;
NSString *myData = [NSString stringWithContentsOfURL:myUrl
encoding:NSUTF8StringEncoding error:&lookupError];
You're first reading the XML data and converting it to an NSString, then later converting that string back into data. As krtrego said, the to-string conversion is probably picking the wrong encoding. Instead, you should feed the raw data from the URL directly into NSXMLParser, which is smarter about being able to interpret the correct encoding (i.e. using the metadata at the top of the XML file.)
So instead use
NSData* myData = [[NSData dataWithContentsOfURL: url options: 0 error: &error];
then pass that data when initializing the NSXMLParser.