2010-03-04 4 views
2

Je voudrais télécharger un fichier mp3 d'un site, l'enregistrer dans mon modèle CoreData, AudioMp3, et le jouer.Téléchargez, enregistrez, et jouez mp3 sur un iPhone

La fonction ci-dessous sorte de travaux, mais d'une part, est inefficace en ce sens qu'il doit d'abord enregistrer le mp3 au fichier, et d'autre part il répète le même mp3 les fois suivantes. Je ne pense pas que ma sauvegarde de base de données est soit juste, où AudioMp3.mp3 est déclarée comme binaire:

- (void) playAndSaveMp3: (NSString*) mp3 { 

NSURL *urlFromString = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@.mp3",@"http://www.somsite.com/mp3/",mp3]]; 

NSData *data = [NSData dataWithContentsOfURL:urlFromString]; 

MyAppDelegate *appDelegate = (MyAppDelegate*)[[UIApplication sharedApplication] delegate]; 

NSManagedObjectContext *managedObjectContext = [appDelegate managedObjectContext]; 

AudioMp3 *audioMp3 = (AudioMp3 *)[NSEntityDescription insertNewObjectForEntityForName:@"AudioMp3" 
                   inManagedObjectContext:managedObjectContext]; 
[audioMp3 setCreationDate:[NSDate date]]; 

[audioMp3 setMp3Name:mp3]; 


//[audioMp3 setMp3:data]; 

// Save to database 
NSError *error; 
if (![managedObjectContext save:&error]) { 
    // Handle the error. 
    NSLog(@"Error in saving new notification. Error: %@", error); 
} 

NSString* resourcePath = [[NSBundle mainBundle] resourcePath]; 
resourcePath = [resourcePath stringByAppendingString:@"/sound.mp3"]; 

[data writeToFile:resourcePath atomically:NO]; 

//declare a system sound id 
SystemSoundID soundID; 

// Get a URL for the sound file 
NSURL *filePath = [NSURL fileURLWithPath:resourcePath isDirectory:NO]; 

// Use audio sevices to create the sound 
AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID); 

// Use audio services to play the sound 
AudioServicesPlaySystemSound(soundID); 

[UIApplication sharedApplication].networkActivityIndicatorVisible = NO; 
} 

Répondre

2

La solution était d'utiliser AVAudioPlayer et la méthode (id) initWithData: (NSData *) Erreur de données: (NSError **) outError. L'enregistrement et le chargement fonctionnent de manière transparente.

Questions connexes