xcode 如何将音频文件从服务器下载到我的 iPhone 应用程序中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13315418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 02:03:16  来源:igfitidea点击:

How to download audio files from a server into my iPhone application?

iphoneiosxcodesdkdownload

提问by 4slices

I have an iphone application which plays audio files (mp3) from a server, I want to add a download button so the user can download these files into the app. So he/she will not need the Internet connection each time they want to listen to these files. Does any one has a sample code for that ?

我有一个从服务器播放音频文件 (mp3) 的 iphone 应用程序,我想添加一个下载按钮,以便用户可以将这些文件下载到应用程序中。因此,他/她每次想要收听这些文件时都不需要 Internet 连接。有没有人有一个示例代码?

I saw many things on the web but I'm still confusion. Here is the code I'm using :

我在网上看到了很多东西,但我仍然很困惑。这是我正在使用的代码:

in the .h File :

在 .h 文件中:

#import 
#import "MBProgressHUD.h"

#import 
#import 

@interface myViewController : UIViewController {
MBProgressHUD *HUD;

long long expectedLength;
long long currentLength;

AVAudioPlayer *theAudio;

}

-(NSString *)pathOfFile;
-(void)applicationWillTerminate:(NSNotification*)notification;

-(IBAction)play:(id)sender;
-(IBAction)download(id)sender;
@property (nonatomic,retain) AVAudioPlayer *theAudio;

in the .m File:

在 .m 文件中:

- (IBAction)download:(id)sender {
NSURL *URL = [NSURL URLWithString:@"http://www.server.com/myfile.mp3"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request      delegate:self];
[connection start];
[connection release];

HUD = [[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES] retain];

HUD.labelText = @"Loading...";
}

-(IBAction)play:(id)sender { 

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *file = [NSString stringWithFormat:@"%@/song.mp3", documentsDirectory];

theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:file]   error:nil];

[theAudio play];

}

-(NSString *)pathOfFile {

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

return [documentsDirectory stringByAppendingFormat:@"myfile.plist"];

}

-(void)applicationWillTerminate:(NSNotification*)notification {

NSMutableArray *array = [[NSMutableArray alloc]init];
[array addObject:theAudio];
[array writeToFile:[self pathOfFile] atomically:YES];

[array release];

}

I don't know what is the problem or what I'm missing over here , can you please help me with more details ? Thanks in advance.

我不知道是什么问题或我在这里遗漏了什么,你能帮我提供更多细节吗?提前致谢。

回答by Khalid Usman

Use ASIHTTP for downloading, it asynchronous and more reliable. http://allseeing-i.com/ASIHTTPRequest/This is the method through which you can download audios/videos. Pass parameter to it and start download?

使用ASIHTTP下载,异步更可靠。http://allseeing-i.com/ASIHTTPRequest/这是您可以下载音频/视频的方法。将参数传递给它并开始下载?

Parameters: (1) File Path , Document Directory path where you want to save (2) Trimmed String , which is the lecture URL

参数: (1) File Path ,要保存的文档目录路径 (2) Trimmed String ,即讲座网址

+ (void)downloadingLecture:(NSString *)filePath withLectureUrl:(NSString *)trimmedString 
 {
    AppDelegate *_appDel=(AppDelegate *)[[UIApplication sharedApplication] delegate];
    [_appDel.queue setDelegate:self];
    [_appDel.queue setMaxConcurrentOperationCount:10];
    [_appDel.queue setShouldCancelAllRequestsOnFailure:NO];
    [_appDel.queue setShowAccurateProgress:YES];

    ASIHTTPRequest *request;
    request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:trimmedString]];
    [request setDelegate:self];
    [request setDownloadDestinationPath:filePath];
    [request setShowAccurateProgress:YES];
    [request setShouldContinueWhenAppEntersBackground:YES];
    [request setUsername:downloadedSuccessfullString];
    [request setDidFinishSelector:@selector(downloadedSuccessfully:)];
    [request setDidFailSelector:@selector(downloadedFailure:)];

    [_appDel.queue addOperation:request];
    [_appDel.queue go];
}

Hope this will help you. If still issue then email me, I am sure I will do it, because I have implemented it in my two applications.

希望这会帮助你。如果问题仍然存在,请给我发电子邮件,我相信我会这样做,因为我已经在我的两个应用程序中实现了它。

回答by iDilip

Try below code:

试试下面的代码:

ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:urlStr]];
[request setDownloadDestinationPath:destinationPath];   
[request setTemporaryFileDownloadPath:[NSString stringWithFormat:@"%@-part",destinationPath]];
[request setDelegate:self];
[request setAllowResumeForFileDownloads:YES];
[request startAsynchronous];

And to check downloads:

并检查下载:

- (void)requestStarted:(ASIHTTPRequest *)request;
- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders;
- (void)request:(ASIHTTPRequest *)request willRedirectToURL:(NSURL *)newURL;
- (void)requestFinished:(ASIHTTPRequest *)request;
- (void)requestFailed:(ASIHTTPRequest *)request; 

Above code will create a file "your_file.mp3-part" in destination folder while download in progress and "your_file.mp3" when download completes.

上面的代码将在下载过程中在目标文件夹中创建一个文件“your_file.mp3-part”,并在下载完成时创建一个“your_file.mp3”。

Hope it helps. Let me know if any doubts.

希望能帮助到你。如果有任何疑问,请告诉我。