下载 mp3 文件,保存到磁盘,并作为 URL 读取

Posted

技术标签:

【中文标题】下载 mp3 文件,保存到磁盘,并作为 URL 读取【英文标题】:Download mp3 file, save to disk, and read it as a URL 【发布时间】:2014-03-04 14:26:29 【问题描述】:

我知道已经有很多关于保存到磁盘的问题,但其中没有一个帮助了我。

在我的应用程序中,我正在使用必须从 url 读取的播放器,并且此 url 不能是流,我的意思是,它必须在设备上。 (因为我正在对音频制作特殊效果,而流式传输对此不起作用)。

所以我像这样下载文件:

      AFHTTPRequestOperation *operation;
   operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) 
    //Secusses

    NSData *resposeObject = responseObject;

       NSArray       *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,   NS  UserDomainMask, YES);
         NSString  *documentsDirectory = [paths objectAtIndex:0];

        NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"filename.mp3"];
        [responseObject writeToFile:filePath atomically:YES];


      failure:^(AFHTTPRequestOperation *operation, NSError *error) 
          //Fail;
     ];

下载后,我需要以 url 的形式播放,方法如下:

   self.audioMusicPlayer = [AEAudioFilePlayer audioFilePlayerWithURL:[NSURL URLWithString:someFile]      audioController:_audioController error:&error]; 

我正在努力理解我的数据如何,可以保存为 mp3 文件,然后播放,作为磁盘上的 url..

我设法播放了我的应用程序中的一个文件而无需下载,它看起来像这样:

NSError *error = nil;
        self.audioMusicPlayer = [AEAudioFilePlayer audioFilePlayerWithURL:[[NSBundle mainBundle]    URLForResource:@"RegevHodBetelemOhavim" withExtension:@"mp3"] audioController:_audioController     error:&error];

编辑

这是我尝试的方式,但它不起作用

     NSArray       *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString  *documentsDirectory = [paths objectAtIndex:0];

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


    /*
      NSError *error = nil;
       self.audioMusicPlayer = [AEAudioFilePlayer audioFilePlayerWithURL:[[NSBundle mainBundle]    URLForResource:@"RegevHodBetelemOhavim" withExtension:@"mp3"] audioController:_audioController    error:&error];
       */

       NSError *error = nil;
       self.audioMusicPlayer = [AEAudioFilePlayer audioFilePlayerWithURL:[NSURL    URLWithString:filePath] audioController:_audioController error:&error]; 

【问题讨论】:

您的问题到底是什么?您的代码是否正常工作,或者您是否在询问“幕后机制”是如何工作的? 有什么问题??下载部分?还是玩家部分?可以用其他播放器播放下载的文件吗? 是的,没有一个有initWithUrl的玩家可以读取这个url,每次都崩溃 如果将 [NSURL URLWithString:filePath] 替换为 [NSURL fileURLWithPath:filePath] 会怎样?顺便说一句,您还应该使用 [documentsDirectory stringByAppendingPathComponent:@"filename.mp3"] 而不是手动创建文件路径,这是处理路径的更好方法。 【参考方案1】:

感谢您的帮助,代码非常好,由于某种未知原因试图在模拟器上运行....对不起!并再次感谢。

【讨论】:

以上是关于下载 mp3 文件,保存到磁盘,并作为 URL 读取的主要内容,如果未能解决你的问题,请参考以下文章

如何在 iOs 或 Android air 项目 (AS3) 上将下载的资产保存到磁盘

基本的http文件在python中下载并保存到磁盘?

基本的http文件下载并保存到python中的磁盘?

使用 Python 请求模块下载并保存 PDF 文件

pygame混音器将音频保存到磁盘?

Alamofire 没有将文件保存到磁盘