Created
April 21, 2011 01:59
-
-
Save wjlafrance/933516 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// DocJohnsonSoundboardModel.m | |
// DocJohnsonSoundboard | |
// | |
// Created by William LaFrance on 4/6/11. | |
// Copyright 2011 William LaFrance. All rights reserved. | |
// | |
#import "DocJohnsonSoundboardModel.h" | |
#define JAVASCRIPT_URL [NSURL URLWithString:@"http://joelandritsch.com/docv_soundboard/clips"] | |
#define FILE_FORMAT @"http://joelandritsch.com/docv_soundboard/clips/%@" | |
@implementation DocJohnsonSoundboardModel | |
@synthesize soundbytes; | |
- (id)init | |
{ | |
self = [super init]; | |
if (self) { | |
// Initialization code here. | |
self.soundbytes = [NSMutableArray array]; | |
NSString *javascript = [NSString stringWithContentsOfURL:JAVASCRIPT_URL | |
encoding:[NSString defaultCStringEncoding] | |
error:nil]; | |
NSArray *files = [javascript componentsSeparatedByString:@"a href=\""]; | |
for (int i = 0; i < [files count]; i++) { | |
NSString *mp3 = [[[files objectAtIndex:i] componentsSeparatedByString:@"\""] objectAtIndex:0]; | |
if ([mp3 rangeOfString:@".mp3"].location != NSNotFound) { | |
[self.soundbytes addObject:mp3]; | |
NSLog(@"This is a mp3 file: %@", mp3); | |
} else { | |
NSLog(@"This is not a mp3 file: %@", mp3); | |
} | |
} | |
} | |
return self; | |
} | |
- (NSURL *)urlForIndex:(NSInteger)index | |
{ | |
return [NSURL URLWithString:[NSString stringWithFormat:FILE_FORMAT, | |
[self.soundbytes objectAtIndex:index]]]; | |
} | |
- (AVAudioPlayer *)playerForIndex:(NSInteger)index | |
{ | |
NSString *filename = [self.soundbytes objectAtIndex:index]; | |
NSError *err = nil; | |
NSURL *url = [self urlForIndex:index]; | |
NSData *soundData = [NSData dataWithContentsOfURL:url]; | |
if (!soundData) { | |
NSLog(@"Failed to load MP3 from internet."); | |
return nil; | |
} | |
NSLog(@"Loaded MP3 from internet."); | |
NSString *dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; | |
NSString *localFilename = [dir stringByAppendingPathComponent:filename]; | |
[soundData writeToFile:localFilename atomically:NO]; | |
NSLog(@"Wrote MP3 to %@", localFilename); | |
AVAudioPlayer *mp3 = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:localFilename] error:&err]; | |
if (!mp3) { | |
NSLog(@"Failed to load: %@", err); | |
return nil; | |
} | |
if ([mp3 prepareToPlay]) { | |
NSLog(@"Prepared to play. Let's go!"); | |
} | |
return mp3; | |
} | |
- (void)dealloc | |
{ | |
self.soundbytes = nil; | |
[super dealloc]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment