Posts Tagged ‘objectivec’
24
set

Do you want use google speech api to recognize text from a dictate?

If you want to add in your “test” project, (test project because it’s not a public API), you need to read Chrome Browser source code.

Here chromium url: src.chromium.org/viewvc/chrome/trunk/src/content/browser/speech

Chrome records audio chunks, accepts only a FLAC file, an open source audio codec (free lossless audio codec) file with a sample rate of 16000.0!

After upload to server:

https://www.google.com/speech-api/v1/recognize

and server responds with a json like this:

1
2
3
4
5
6
7
8
9
10
11
12
{
    "status": 0,
    "id": "f3847b5dcu4d657f6667f3pk4sc0a8ca-2",
    "hypotheses": [
    {
        "utterance": "it works",
        "confidence": 0.8012238
    },
    {
        "utterance": "it works"
    }]
}

Now, using ASIFormDataRequest we can send in POST a file to google url waiting for JSON.
Objective-c code:

1
2
3
4
5
6
7
8
9
10
11
12
13
- (void) SpeechFromGooglezzz {
  NSURL *url = [NSURL URLWithString:@"https://www.google.com/speech-api/v1/recognize?xjerr=1&client=chromium&lang=en-US"];

  ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
  NSString *filePath = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath], @"tmpAudio.flac"];

  NSData *myData = [NSData dataWithContentsOfFile:filePath];
  [request addPostValue:myData forKey:@"Content"];
  [request addPostValue:@"audio/x-flac; rate=16000" forKey:@"Content-Type"];
  [request startSynchronous];

  NSLog(@"req: %@", [request responseString]);
}

But now is there a big problem… objective-c and iphone don’t recognize FLAC files, you need an intermediate passage to send the correct audio file.

Set up your server with FFMPEG (an audio/video converting/editing tool) and prepare a PHP/JSP/etc. that accept in post an audio file, call a PHP EXEC and launch ffmpeg with flac codec.
Then upload from server to google and return response!

Here code to record and listen audio file from iPhone. Create two buttons and copy/paste code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
- (IBAction)StartRec:(id)sender {  
  NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
                            [NSNumber numberWithFloat: 16000.0],                 AVSampleRateKey,
                            [NSNumber numberWithInt: kAudioFormatMPEGLayer3],    AVFormatIDKey,
                            [NSNumber numberWithInt: 1],                         AVNumberOfChannelsKey,
                            [NSNumber numberWithInt: AVAudioQualityMax],         AVEncoderAudioQualityKey,
                            nil];
 
  NSError *error;
  NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath], @"tmpAudio.mp3"]];
  recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];
 
  if (recorder) {
    [recorder prepareToRecord];
    [recorder record];
  }
  else NSLog(@"%@", [error description]);
}
1
2
3
4
5
6
7
8
9
10
11
12
- (IBAction)PlayAudio:(id)sender {
 NSString *path = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath], @"tmpAudio.mp3"];
 
 SystemSoundID soundID;  
 NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
 AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
 AudioServicesPlaySystemSound(soundID);
}

- (IBAction)StopRec:(id)sender {
  if (recorder) [recorder stop];
}

That’s all, enjoy!

…and remember that speech function of google it’s a private API. You can’t use in a commercial app!

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , , , , , , , ,

07
mag

Hi all!!
Today i show how is possible to connect iPhone to Arduino without any Wifi or Ethernet shields!

Here the app that controls 4 leds (green yellow, red and orange), a DC motor with a fan, a piezo speacker and the room temperature with LM32 sensor!


Arduino iphone control


What you need?
Arduino with anything you want
iPhone / iPad / iPod
– A website to host php pages
– An internet connection on pc (Win + Mac)

What you need to know?
– A little bit of electronics
C language
C# language
PHP language
Objective-C language

Good.
In PHP make a stupid page that get in $_REQUEST a command and store it to a file on server!
Three lines of code…

In C# make a web listener that call php page and checks the output. If any condition are verified, send to COM9 the value that you want to get from arduino.

In C from Arduino, in the Loop() read Serial value. If the value respond to your configuration, call LigthUpLed(green) for example!

In Objective-C make an iPhone App with a stupid layout that call in GET your PHP page and send a command!

To make everithink work, run your C# listener app on Windows and from your iPhone send get call to web server!

Now, your nerd app will control arduino!!!

In this example app that i made, i control HIGH or LOW for Four LEDs, a DC Motor, a Piezo Speacker and a Temperature Sensor.

I used resistors, 4 leds, LM32, DC Motor, TIP120, diode, wires, beer.




Here a screenshot (click to enlarge):


Arduino iphone control

Here a video:



Rif: albertopasca.it

enjoy!

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , ,

11
gen

Get current and formatted time from your simulator or device!

1
2
3
4
5
6
7
8
9
10
11
12
13
- (NSString*) getDateTime {
     NSDateFormatter *formatter;
     NSString        *dateString;
 
     formatter = [[NSDateFormatter alloc] init];
     [formatter setDateFormat:@"dd-MM-yyyy HH:mm"];
 
     dateString = [formatter stringFromDate:[NSDate date]];
     [formatter release];

     NSLog(@"Current data: %@", dateString);
     return dateString;
}

eof

Rif: albertopasca.it

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , ,

09
gen

Hi all,
this is a simple way to add programmatically a “Person” into your iphone contacts list.

First of all you need to include Address Book frameworks into your project:

#import AddressBook/AddressBook.h
#import AddressBookUI/AddressBookUI.h





After that, create an IBAction or something else and paste this function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
- (IBAction) addToContacts {
        ABAddressBookRef iPhoneAddressBook = ABAddressBookCreate();
        ABRecordRef newPerson = ABPersonCreate();

        // add infos
        ABRecordSetValue(newPerson, kABPersonFirstNameProperty, CFSTR("Alberto"), nil);
        ABRecordSetValue(newPerson, kABPersonLastNameProperty, CFSTR("Pasca"), nil);
        ABRecordSetValue(newPerson, kABPersonOrganizationProperty, CFSTR("albertopasca.it"), nil);

        ABMutableMultiValueRef multiPhone = ABMultiValueCreateMutable(kABMultiStringPropertyType);
 
        ABMultiValueAddValueAndLabel(multiPhone, @"328-1111111", kABHomeLabel, NULL);
        ABMultiValueAddValueAndLabel(multiPhone,@"02-222222", kABWorkLabel, NULL);
        ABRecordSetValue(newPerson, kABPersonPhoneProperty, multiPhone,nil);
        CFRelease(multiPhone);
 
        ABMutableMultiValueRef multiEmail = ABMultiValueCreateMutable(kABMultiStringPropertyType);

        ABMultiValueAddValueAndLabel(multiEmail, @"info@albertopasca.it", kABHomeLabel, NULL);
        ABRecordSetValue(newPerson, kABPersonEmailProperty, multiEmail, nil);

        // add an image !
        UIImage *im = [UIImage imageNamed:@"logo_mobile_48.png"];
        NSData *dataRef = UIImagePNGRepresentation(im);
        ABPersonSetImageData(newPerson, (CFDataRef)dataRef, nil);

        CFRelease(multiEmail);
 
        ABAddressBookAddRecord(iPhoneAddressBook, newPerson, nil);
        BOOL didAdd = ABAddressBookSave(iPhoneAddressBook, nil);

        CFRelease(newPerson);
        CFRelease(iPhoneAddressBook);
}

All the contact properties are hidden in kAB*******. Try it!

It’s all!!!

enjoy!




Rif: albertopasca.it

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , , , , , , ,

16
nov

You have a long text and doesn’t fill your screen?
It’s a simple snippet to trim the string and append three dots (…).

This is a long str…

1
2
3
4
5
6
 NSRange stringRange = {0, MIN([aText length], 25)};
 stringRange = [aText rangeOfComposedCharacterSequencesForRange:stringRange];

 NSString *shortString = [aText substringWithRange:stringRange];
 shortString = [[aText substringWithRange:stringRange]
                                          stringByAppendingString:@"..."];

enjoy!





Rif: albertopasca.it

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , , , , , , ,

27
ott

Here a simple tutorial to use SQLite in Objective-C to make complex iphone|ipad applications that uses a database!

First of all, you NEED to download Firefox, after that you need to download and install SQLite Manager Add On for Firefox from here.
The plugin will be used later…

Now, create a new project and import SQLite library. Generally it is located here:

/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.X.X.X.sdk/usr/lib/libsqlite3.dylib

Firefox!

In your header file, you need t add the import and create sqlite3 class in your interface:

1
2
3
#import <sqlite3 .h>
[...]
sqlite3 *database;

I show only three method that uses the db, SELECT, DELETE, INSERT.





READ DATA (like SELECT * FROM XXX)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
- (NSMutableArray*) readDataFromDatabase
{
   dataArray  = [[NSMutableArray alloc] init];
   dataStored = [[NSMutableDictionary alloc] init];
   
   NSString *name;
   NSString *address;
 
   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
   NSString *documentsDirectory = [paths objectAtIndex:0];
   NSString *path = [documentsDirectory stringByAppendingPathComponent:@"MyDB.sqlite"];
 
   if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
      const char *sql = "SELECT * FROM tabella";
      sqlite3_stmt *statement;
      if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
         while (sqlite3_step(statement) == SQLITE_ROW) {
            name =   [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
            address = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
   
            [dataStored setObject:name forKey:@"name"];
            [dataStored setObject:address forKey:@"address"];
   
            [dataArray addObject:[dataStored copy]];
         }
      }
      sqlite3_finalize(statement);
   }
   sqlite3_close(database);
   [dataStored release];

   return dataArray;
}

In this method, that return a NSMutableArray, I used a NSMutableDictionary (dataStored) and a NSMutableArray (dataArray).
Now we have a dataArray with lists of the select query!

Continue reading “[Objective-C] Use database with sql (lite)” »

FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , , , , , ,

27
ott

A simple ‘promemoria’!

1
2
3
4
5
6
7
8
9
10
11
12
13
[self.delegate
   performSelectorOnMainThread:@selector(setMapType:)
   withObject:@"a obj"
   waitUntilDone:NO];

[NSThread
   detachNewThreadSelector:@selector(parseData:)
   toTarget:self.delegate
   withObject:@"a obj"];

[aView
   performSelector:@selector(removeView)
   withObject:@"a obj"];
FacebookTwitterDeliciousLinkedInGoogle BookmarksNetlogGoogle GmailMySpaceGoogle ReaderShare

, , , , , , , , ,

Switch to our mobile site