Создание аудиокниг для iPod/iPhone

May 12th, 2010 vira Posted in mac 3 Comments »

Ваш iPod умеет проигрывать аудиокниги – т.е. он просто запоминает позицию, на которой Вы закончили прослушивание. Формат поддерживаемых им аудиокниг  - m4b, но по сути это обычный m4a (”любимый” формат Apple для хранение музыки, используется в iTunes, iPod и тп.). Но проблема в том, что “у нас” аудиокниги обычно выкладывают в виде нескольких mp3-шек, чтобы было возможно слушать проигрывателями, которые не умеют запоминать место, где Вы закончили “читать” книгу. Но как оказалось, из этого набора mp3 файлов достаточно легко сделать аудиокнигу для iPod-а.

Т.е. чтобы создать аудиокнигу в формате m4b для Apple-”мира” необходимо:

  1. Соединить все mp3-шки в одну. Можно сделать это в терминале при помощи команды “cat”: cat *.mp3 > outputAudioBook.mp3
  2. Далее этот большой mp3-и файл добавить в iTunes (можно временно отключить копирование музыки в iTunes Library, чтобы не засорять ее и для скорости) и сконвертировать  в формат m4a: в главном меню Advanced -> “Create AAC Version”
  3. Далее в iTunes в контекстном меню для этого файла “Show in Finder” и меняем расширение на “m4b”.
  4. Удаляем оба файла (m4a и mp3) из iTunes. И добавляем m4b. Он должен появиться в разделе “Books”. Если этого раздела нет, то его можно включить в настройках, вкладка “General”.

Вот и все. Далее эти книги можно синхронизировать с iPod/iPhone.

Приятного прослушивания :)


Using Google AJAX search API in Cocoa

January 8th, 2010 vira Posted in Computer science, mac 2 Comments »

Sometimes it’s needed to allow user to find some information in the Web, without interrupting he/she from working with your application. In this small article I’ll describe simple solution to fulfill this task.
As for today, search = Google and I’m going to implement search using it. I’ve implemented category for Cocoa’s NSArray class for creating array of dictionaries. Each dictionary represents a search results. You can define where to search (web, news, video) etc and how many results to return. This code requires JSON Framework by Stig Brautaset

Here is the code of the main search method. The full project can be downloaded here (XCode 3.2, JSON Framework included)

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
+ (NSArray *)arrayWithSearchFor:(NSString *)query type:(NSString *)searchType range:(NSRange)range
{
    if (range.location > 56) {
    	NSLog(@"Error while searching in Google : start must be in range [0;56]");
    	return nil;
    }
 
    NSMutableArray *results = [NSMutableArray array];
    SBJSON *parser = nil;
    NSString *json_string = nil;
    NSUInteger i = range.location;
 
    while (i < range.length + range.location) {
        @try {
    	    NSURL *url = [NSURL URLWithString:[BASE_URL stringByAppendingFormat:@"%@?v=%@&q=%@&start=%i", searchType, @"1.0", query, i]];
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                        cachePolicy:NSURLRequestReloadIgnoringCacheData
                                        timeoutInterval:120];
            NSError *error = nil;
            NSURLResponse *response = nil;
            NSData *searchResults = [NSURLConnection sendSynchronousRequest:request
                                         returningResponse:&response
                                        error:&error];
            if (!searchResults) {
                        @throw [NSException exceptionWithName:@"Failed to search cuz: %@" reason:[error description] userInfo:nil];
            }
            //parse results
            parser = [[SBJSON alloc] init];
            json_string = [[NSString alloc] initWithData:searchResults encoding:NSUTF8StringEncoding];
 
            //NSLog(@"Raw JSON result %@", json_string);
            NSDictionary *allResult = [parser objectWithString:json_string error:&error];
            if (!allResult || [allResult isKindOfClass:[NSNull class]]) {
                    @throw [NSException exceptionWithName:@"Failed to parse all results JSON" reason:[error description] userInfo:nil];
            }
            if (![[allResult objectForKey:@"responseStatus"] isEqualToNumber:[NSNumber numberWithInt:200]]) {
                @throw [NSException exceptionWithName:[allResult objectForKey:@"responseStatus"] reason:[allResult objectForKey:@"responseDetails"] userInfo:nil];
            }
            allResult = [allResult objectForKey:@"responseData"];
            if (!allResult || [allResult isKindOfClass:[NSNull class]]) {
                @throw [NSException exceptionWithName:@"Failed to parse responseData" reason:[error description] userInfo:nil];
            }
            NSArray *newResults = [allResult objectForKey:@"results"];
            if (!newResults) {
                @throw [NSException exceptionWithName:@"Failed to parse results" reason:[error description] userInfo:nil];
            }		
 
            [results addObjectsFromArray:newResults];
            i += SMALL_RESULT_SET;
        } @catch (NSException * e) {
            NSLog(@"Exception during searching in Google: %@", e);
        } @finally {
            [parser release];
            [json_string release];
        }
    }
    return results;
}
 
+ (NSArray *)arrayWithWebSearchFor:(NSString *)query range:(NSRange)range
{
    return [[self class] arrayWithSearchFor:query type:WEB_URL range:range];
}

And the sample usage:

1
2
3
4
5
NSArray *results = [NSArray arrayWithWebSearchFor:@"apple" range:NSMakeRange(0, 5)];
    NSLog(@"Search finished, found %i", [results count]);
    for (NSDictionary *result in results) {
        NSLog(@"Url = %@",  [result objectForKey:@"url"]);
    }

In this sample code I’ve searched for “apple” and got the following results:

2009-10-13 01:18:40.638 iGoogle[63665:a0f] Url = http://en.wikipedia.org/wiki/Apple_Inc.
2009-10-13 01:18:40.641 iGoogle[63665:a0f] Url = http://www.info.apple.com/
2009-10-13 01:18:40.641 iGoogle[63665:a0f] Url = http://www.crunchbase.com/company/apple
2009-10-13 01:18:40.642 iGoogle[63665:a0f] Url = http://developer.apple.com/
2009-10-13 01:18:40.642 iGoogle[63665:a0f] Url = http://apple.slashdot.org/
2009-10-13 01:18:40.642 iGoogle[63665:a0f] Url = http://finance.yahoo.com/q%3Fs%3DAapl
2009-10-13 01:18:40.644 iGoogle[63665:a0f] Url = http://support.apple.com/batteryprogram/
2009-10-13 01:18:40.644 iGoogle[63665:a0f] Url = http://topics.nytimes.com/topics/news/business/companies/apple_computer_inc/index.html

This code has never been used in production, so use on your own risk ;-)


Open all icons on your Mac

November 6th, 2009 vira Posted in fun, mac No Comments »

Just for fun :) I decided to discover if it possible to open all icons (.icns files) with Preview and (as in real experiment) to measure how many resources this operation will take. To perform this I executed the following shell command:

find / -name *.icns -exec open {} \;

It is also better to change Preview preferences to make it open all files in one window (it isn’t a good idea to open thousands of windows). And here is the results for my system

MacBookPro5,4/Intel Core 2 Duo 2,53 GHz/4 GB DDR3/MacOS X 10.6.1

Preview resources consumption

So, it’s taken about 45 minutes and 850 MB of memory to found 4144 icons on my system… It’s possible to work with all this icons in Preview, search in them and so on. But generating of PDF file from all these icons failed (in fact I cancelled it when Preview had “ate” 2 GB of memory :) ). Here is screenshot of all this beauty.

All Icons in Preview

This could be useful for designers/programmers for researching/”stealing” icons.

E.g. I was surprised how the icon for “downloading in progress” file is drawn.

screen-shot-2009-11-06-at-00.22.17.png


People Net и Mac

April 17th, 2009 vira Posted in internet, mac No Comments »

По причине отсутствия интернете в моем родном городе Комсмольске решилась я таки купить какое-нибудь 3G решение. Выбор пал на People Net, в большей степени из-за раскрученности и в меньшей после сравнения с конкурентами :)

Выбора модемов в отделении Приват-банка (где также можно подключиться) особого не было и “пришлось” брать Huawei EC 226. Не совсем пальцем в небо конечно – он поддерживает маки и вроде бы неплохой по отзывам.

На сайте people net-a в разделе этого модема есть драйвера под мак и инструкция, но! Сразу у меня ничего естественно не получилось. При подключении выдавало “No carrier detected…” Как оказалось, необходимо просто отключить проверку PIN-кода под Windows из программы Mobile Partner, которая поставляется с модемом. Жаль этого не описано в официальной инструкции.

И еще один момент, драйвера написаны довольно таки криво и забивают syslog всякой гадостью. Вроде бы связано с тем, что модем заявляет себя как cd-rom, но примаунтить его не выходит. Попытки постоянно повторяются и в результате получаем никому не нужную нагрузку на систему. Надо будет разбираться, более детально тут.

P.S. Скорость довольно таки нормальная, порой лучше киевской Воли кабель :)


XCode tips

March 31st, 2009 vira Posted in Computer science, mac No Comments »

Here will be short list of the XCode hotkeys most used by me. I’ll try to update it periodically.

  • Switch to header/source file – Opt+Cmd+Up
  • Show Console – Shift+Cmd+R
  • Move to the next argument in Code Completion – Control+slash
  • Jump to definition – Cmd+doubleClick
  • Code Completion – Esc
  • Open Quickly – Shift+Cmd+D

Cool shortcut’s list for XCode


Back your Mac to life

December 26th, 2008 vira Posted in mac 1 Comment »

Перезапускаю свой ноут я обычно в случаях крайней необходимости – апдейты поставить или просто что-то перестало/стало медленно работать.

Так и случилось на днях, пришлось перезапустить после апйдетов Safari и iTunes… Но после перезапуска загрузка доходила только для логин скрина… В этом посте я попытаюсь вкратце передать свой опыт воскрешения макос-а.

Read the rest of this entry »


Ваш МакБук уже не очень белый – тогда ацетон идет к Вам :)

November 10th, 2008 vira Posted in mac 2 Comments »

Как известно, со временем корпус белого МакБука желтеет и не доставляет былого эстетического удовольствия. В моем случае, визуальный дефект еще больше усилился после установки нового аккумулятора – его белая поверхность делала корпус еще желтее.

 Результат от средств, которые советовали на всяческих форумах/блогах и т.п. (а это были средства для чистки дисков и зубной порошок),  меня не удовлетворил… и я решила подойти к вопросу радикально – снять верхний слой пластмассы (благо он довольно толстый)  с помощью растворителя. Эдинственное что было под рукой – жидкость для снятия лака для ногтей – отлично справилось со своей задачей. Корпус стал как новый и аккумулятор его не позорит теперь :-) Эдинственное замечание – надо быть осторожными с  текстом/значками на корпусе… ато у меня уже аудио выход не подписан….

Возможно это не самый щадящий метод очистки, но довольно дешевый, доступный, эффективный и мне помог :)  


WWDC 2008!

June 9th, 2008 vira Posted in mac No Comments »

Уже началось! Одна из текстовых/фото трансляций на инглише MacRumorsLive. Приятного прочитывания )


True MacCat

June 5th, 2008 vira Posted in All, mac 6 Comments »

Фотосессия моей кошки Ассы – истинной фанатки “теплой” продукции Apple. Правда рассматривает MacBook  она исключительно как место для сна :-) Отношения Ассы с ноутбуком были исследованы и задокументированы. Фото под катом. Read the rest of this entry »


MacBook Air – thinner than the the thinnest part of a Sony TZ series laptop

January 16th, 2008 vira Posted in mac 1 Comment »

Умеет Apple интриговать – люди ждут их релизов, как второго пришествия :) На моей памяти – iPhone, Leopard и теперь вести из ключевого доклада Стива Джобса, разгадка загадки “There is something in the air” – This is MacBook Air. И он действительно буквально парит в воздухе.

MacBook Air

Read the rest of this entry »