【发布时间】:2010-03-04 08:26:42
【问题描述】:
我想从某个站点下载一个 mp3 文件,将其保存到我的 CoreData 模型 AudioMp3 中并播放它。
下面的函数有点工作,但首先,它效率低下,因为它必须首先将 mp3 保存到文件中,其次它在随后的调用中重复播放相同的 mp3。我认为我的保存到数据库也不正确,其中 AudioMp3.mp3 被声明为二进制:
- (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;
}
【问题讨论】:
标签: iphone core-data core-audio