2010-03-04 74 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。保存和加載工作無縫。