iOS版 - 从阅读文档目录的音频文件(iOS - Reading an Audio file fr

2019-10-23 14:54发布

我保存音频数据的文件目录,并试图读回。 如果我马上打回它成功播放,但是,如果我开始一个新的会话和尝试,并播放这首歌曲在本地会失败,即使在文件列表中的文件目录显示我的文件仍然存在。 需要注意的是该文件,如果它立即或新的会话过程中起到相同的方式(相同的代码)从Documents文件夹播放。

下面是我如何保存音频数据的文件目录:

+(void)writeDataToAudioFile:(NSData*)data forTrack:(MediaItem*)track
{
    // filename looks like "[track_id].mp3" 
    NSString *fileName = [NSString stringWithFormat:@"%@.%@",track.sc_id,track.original_format];

    NSString *pathName = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                                  NSUserDomainMask,
                                                                  YES) firstObject]
                             stringByAppendingPathComponent:fileName];

    [[NSFileManager defaultManager] createFileAtPath:pathName
                                            contents:data
                                          attributes:nil];
}

然后在我的音乐播放器我​​想当地的URL加载到这个文件来初始化AVPlayer:

NSURL *url;
    if(_currentTrack.is_local_item)
    {
          url = [NSURL fileURLWithPath:_currentTrack.local_file_path];
    }

网址未得到适当的创建为AVPlayer不玩了。 此外,我都想尽不同的方式将文件数据加载到一个NSData对象来检查字节大小,但试图访问文件数据总是返回零。 然而,该文件存在,如果我使用的NSFileManager我能够遍历在Documents目录中的项目并打印其文件名/路径,表明我我已经保存在“_currentTrack.local_file_path”的路径确实存在。 再次,如果我将文件保存到磁盘后立即播放该文件就会播放。

如果有更多的信息,我可以提供,使这个更清楚我会的。 非常感谢你。

Answer 1:

不要写入数据库的完整目录路径。 它会改变。 您只需要在文件名保存DB作为参考。 然后使用方法如下:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; 
NSString *fileName = @"SAVED_FILE_NAME.mp3"; // eg: [track_id].mp3
NSString *filePath = [documentsPath stringByAppendingPathComponent:fileName]; 

这将为您提供文件的实际路径。

保持编码........... :)



Answer 2:

I found the solution after putting the problem down for a few days. I break-pointed and print-stated the heck out of the program and I found that the file path I was saving was not the same as the file path of the file.

I think this was a simulator issue, as the issue only occurred between different sessions of the simulator, and worked within the same session, so the device id (which is part of the absolute path) was changing - maybe someone more knowledgeable can weigh in on that.

Pay closer attention to the string values of your variables folks!



文章来源: iOS - Reading an Audio file from Documents Directory