本文介绍了下载,保存和在iPhone上播放mp3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从某个网站下载一个mp3文件,保存到我的CoreData模型,AudioMp3,并播放它。

I would like to download an mp3 file from some site, save it to my CoreData model, AudioMp3, and play it.

但首先,效率不高,因为它必须首先将mp3保存到文件,其次它播放相同mp3的重复,在下面的时间被调用。我不认为我的保存到数据库是正确的,其中AudioMp3.mp3声明为二进制:

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;
}


推荐答案

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

The solution was to use AVAudioPlayer and the method (id)initWithData:(NSData *)data error:(NSError **)outError. Saving and loading work seamlessly.

这篇关于下载,保存和在iPhone上播放mp3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 04:52