2010-03-04 95 views
2

我想从某个网站下载一个mp3文件,将其保存到我的CoreData型号AudioMp3中并播放它。在iPhone上下载,保存和播放MP3

下面的函数可以工作,但首先效率不高,因为它必须首先将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; 
} 

回答

2

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