我想音频文件(这些格式MP3,WAV,和iPhone的支持)存储在数据库和iPhone上播放他们......任何想法如何做到这一点?
Answer 1:
我不知道你为什么会想将音频文件存储在SQL数据库,但sqlite3的支持BLOB。 所以将它们存储为BLOB和检索。
或者为什么不储存要播放的文件引用?
Answer 2:
一般来说,最好不是二进制文件存储在任何数据库。 您是关书面文件来对磁盘文件,然后在数据库中存储的路径更好。
Answer 3:
这并不总是最好的存储磁盘上的文件。 看看这个比较:
http://www.sqlite.org/intern-v-extern-blob.html
下面是一个使用Ruby和续集宝石它,我该怎么办:
创建使用该架构的一个表。 该文件是一个blob,啥是文件的名称。 在这种情况下,我的所有文件都是可变比特率单声道MP3文件,2K-3K的大小。 我在DB约40 000文件。 我使用SHA1值作为文件名,因为我有很多有相同的声音,所以我节省一些空间条目。
CREATE TABLE `sound` (`id` integer PRIMARY KEY AUTOINCREMENT, `sha` text, `file` blob); CREATE INDEX `sound_sha_index` ON `sound` (`sha`);
使用Ruby,你可以创建一个这样的数据库:
db = Sequel.sqlite('./sound.db')
db.create_table :sound do
primary_key :id, :index => true
column :sha, :text, :index => true
column :file, :blob
end
将文件加载到数据库中。 假设你有一个名为“声音”目录中的文件,这里是如何:
DB = Sequel.sqlite('./sound.db')
files = Dir['./sound/*.mp3']
files.each_with_index do |f, i|
# progress
print "\r #{((i.to_f / files.size)*100).round(2)}%"
# get the file name without directory and extension
f =~ /\/sound\/(.+)\.mp3/
# insert into db
DB[:sound].insert :sha => $1, :file => File.read("#{f}").to_sequel_blob
end
在iPhone应用程序播放声音。 该sound.db文件复制到你的iPhone项目。 这是我使用的代码。 它基于FMDB和AVAudioPlayer。
SoundPlayer.h
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
#import "FMDatabase.h"
#import "FMDatabaseQueue.h"
@interface SoundPlayer : NSObject
{
FMDatabaseQueue *db;
}
@property (nonatomic, retain) AVAudioPlayer *audioPlayer;
- (void)play:(NSString *)sha;
- (void)free;
@end
SoundPlayer.m
#import "SoundPlayer.h"
#import "DictAppDelegate.h"
@implementation SoundPlayer
- (SoundPlayer*)init
{
NSString *dbPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"sound.db"];
db = [FMDatabaseQueue databaseQueueWithPath: dbPath];
return self;
}
- (void)play:(NSString *)sha
{
[db inDatabase:^(FMDatabase *connection) {
// Execute and fetch result
NSString *query = [NSString stringWithFormat:@"select file from sound where sha = '%@' limit 1", sha];
FMResultSet *rs = [connection executeQuery:query];
while([rs next]) {
NSData *file = [rs dataForColumn: @"file"];
NSError *error;
self.audioPlayer = [[AVAudioPlayer alloc] initWithData: file error:&error];
self.audioPlayer.numberOfLoops = 0;
self.audioPlayer.volume = 1.0f;
[self.audioPlayer prepareToPlay];
if (self.audioPlayer == nil) {
NSLog(@"Error playing sound: %@", [error description]);
} else {
[self.audioPlayer play];
}
}
}];
}
// Cleanup
- (void)free {
[db close];
}
@end
使用从某处的文件在你的代码是这样的:
self.soundPlayer = [[SoundPlayer alloc] init];
[self.soundPlayer play:[entry valueForKey:@"sha"]];
其中[进入valueForKey:@“SHA”]]返回的NSString这是我一直保存在我的项目的其他表的文件名。
文章来源: how do i store audio files in sqlite3 database and play them in iphone?