IOS 学习笔记(Play Audio,Http Request,Parse html)PART 9

今天和Andy君喝了StarFuck,了解到了他正在做的事是如此地牛逼闪闪,我自愧不如,他真的非常适合做独立开发者。我还有待修炼,所以丝毫不敢偷懒。

先分享一本据说是最怪的百科全书,Codex.Seraphinianus.

Play Audio

目前了解到的播放一段音频的方法有两个,第一种比较麻烦,是用来播放本地(文中提到)音频文件的,首先,将音频文件放置到项目中,这里以mp3文件为例,需要添加AudioToolBox.framework,之后代码如下:

NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:soundName ofType:@"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];

self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self.audioPlayer setVolume:1.0];
self.audioPlayer.delegate = self;
[self.audioPlayer stop];
[self.audioPlayer setCurrentTime:0];
[self.audioPlayer play];

这里值得说的是,不同通过定义临时变量的方式定义AVAudioPlayer,必须在Class中指定Strong的property来存放它,否则它会在ARC机制下还没有播放声音就被release了。

之后可以通过实现AVAudioPlayerDelegate,来响应播放完毕时的处理:

- (void) audioPlayerDidFinishPlaying: (AVAudioPlayer *) player successfully: (BOOL) flag{
    //do something after sound played.
}

当想要播放一个在线存放的音频文件时,AVAudioPlayer就不灵了,要用AVPlayer,嗯,好名字,需要添加AVFoundation.framework。

-(void)playSound:(NSString *)soundFilePath{

    NSURL *url = [NSURL URLWithString:soundFilePath];
    self.playerItem = [AVPlayerItem playerItemWithURL:url];
    self.songPlayer = [AVPlayer playerWithPlayerItem:self.playerItem];
    [self.songPlayer play];
}
- (void)playerItemDidReachEnd:(NSNotification *)notification {

    //  code here to play next sound file

}

Get Data With Http Request

NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
NSData *data = [NSData dataWithContentsOfURL:url];

Parse Html

这里用到了这篇文章,其中提到的开源项目Hpple,打开后Copy下图所示的文件到项目文件夹。

由于hpple使用了libxml2包,所以需要告诉它头文件在哪,做法是,在项目属性界面的Build setting中搜索,“header search paths”,然后加入这一行,$(SDKROOT)/usr/include/libxml2。然后再将libxml2.dylib,添加到Link Binary With Libraries中。

下面是使用的代码:

TFHpple *tutorialsParser = [TFHpple hppleWithHTMLData:data];
NSString *tutorialsXpathQueryString = @"//a[@class='audio']";
NSArray *tutorialsNodes = [tutorialsParser searchWithXPathQuery:tutorialsXpathQueryString];
TFHppleElement *element = tutorialsNodes[0];
//get html element attributes
[[element attributes] objectForKey:@"data-url"];
//get html element text
[element text]