问题
I would like to download an mp3 file from some site, save it to my CoreData model, AudioMp3, and play it.
The function below sort of works, but firstly, is inefficient in that it has to save the mp3 to file first, and secondly it plays a repeat of the same mp3 the following times it is called. I don't think my save to database is right either, where AudioMp3.mp3 is declared as binary:
- (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;
}
回答1:
The solution was to use AVAudioPlayer and the method (id)initWithData:(NSData *)data error:(NSError **)outError. Saving and loading work seamlessly.
来源:https://stackoverflow.com/questions/2377787/download-save-and-play-mp3-on-an-iphone