在iPhone上下载,保存和播放mp3

时间:2010-03-04 08:26:43

标签: iphone core-data core-audio

我想从某个网站下载一个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;
}

1 个答案:

答案 0 :(得分:2)

解决方案是使用AVAudioPlayer和方法(id)initWithData:(NSData *)数据错误:(NSError **)outError。无缝保存和加载工作。