Download, save, and play mp3 on an iPhone

会有一股神秘感。 提交于 2019-12-21 06:08:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!