How to store audio file in sqlite database in iOS

别等时光非礼了梦想. 提交于 2019-12-12 09:27:34

问题


I am developing an iPhone application for an audio player. I want to give some options to the user so they can listen to the song/music by streaming or they can download the audio file and store in sqlite database. I know how to stream the audio files in the app programmatically. But I don’t know how to store the downloaded audio file in sqlite database using BLOB. Additionally, after storing the audio file in the sqlite DB I need to fetch the audio file and play the song. How do I fetch the audio file from sqlite DB?

This is my code for downloading the audio file.

NSURL *url = [NSURL URLWithString:@"http://www.fileurl.com/example.mp3"];

ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];

[request setDownloadDestinationPath:[NSString stringWithFormat:@"%@",dataPath]]; 

[request setDelegate:self];

[request startAsynchronous];

回答1:


I don't recommend to store binary files in database as blobs. it will make you a problem with growing database file size in future. You will have to implement smart vacuum operation which is very slow on large data amounts. My strong opinion: the files must be stored in file system. Store your file in application Documents folder and store a kind of link to them in database.




回答2:


you can download file and write audio file using NSDocumentDirectory in app. Documents folder like

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"audio.mp3"]];
[{your audio file in NSData} writeToFile:path atomically:YES];

now store only "audio.mp3" in database

when you retrieve data from database that give you name like

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:{database store name}]];

note if you store full path that not working because Documents foldar path change whenever you run app.



来源:https://stackoverflow.com/questions/36280264/how-to-store-audio-file-in-sqlite-database-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!