ios录音文件路径_iOS版 - 读从Documents目录音频文件

I am saving audio data to the Documents directory and trying to read it back. If I play it back immediately it plays successfully, however, if I start a new session and try and play the song locally it will fail even though listing the files in the Documents directory shows that my file is still there. Note that the file is played back from the Documents folder in the same way (same code) if it is played immediately or during a new session.

Here is how I save the audio data to the Documents directory:

+(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];

}

Then in my music player I want to load the local URL to this file to initialize the AVPlayer:

NSURL *url;

if(_currentTrack.is_local_item)

{

url = [NSURL fileURLWithPath:_currentTrack.local_file_path];

}

url does not get created properly as AVPlayer does not play. Furthermore, I have tried every different way to load the file as data into an NSData object to check the byte size but trying to access the file as data always returns nil. However, the file exists as if I use NSFileManager I am able to iterate over the items in the Documents directory and print their file names/paths, validating that I the path I have saved in "_currentTrack.local_file_path" does exist. Again, if I play the file immediately after saving the file to disk it will play back.

If there is more info I can provide to make this clearer I will. Thank you very much.

解决方案

Do not write the full directory path to DB. It will change. You need to only save the file name to DB as reference. Then use as follows:

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

This will provide you the actual path of the file.

Keep coding........... :)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值