`
wonderzl
  • 浏览: 79034 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

将声音存入SQLite3数据库

阅读更多
    iPhone开发中,很多时候要用到播放声音,但是直接将声音放入工程中势必造成Resources中文件太多,这样就需要将声音存入SQLite3数据库。以下为代码:

public class WriteVoice2DB {

	public void WriteVoice2DB() {
		System.out.println("Create WriteVoice2DB instance!");
	}
	
	public static void main(String[] args) {
		try {
			WriteVoice2DB wvdb = new WriteVoice2DB();
			wvdb.savabinay();
			
		} catch (Exception e) {
			e.printStackTrace();
		}

	}



	public void savabinay() throws rdeSQLiteException {
		rdeSqlite3DB database = new rdeSqlite3DB();
		database.open("Spanish_voice1.dat");
		database.ExecSQL("CREATE TABLE voice_binary_table('id' CHAR(30) PRIMARY KEY, 'filename' CHAR(30), 'audioBinary' blob)");

		//read the file stream 
		byte[] dataArray = {};
		try {
			File f = new File("C:/Documents and Settings/liu/My Documents/My Music/waiting.wav");
			dataArray = read2list(f);
			System.out.println(dataArray.length);
			
			//save in DB 
			StringBuffer sb = new StringBuffer();
			String insertSql = "INSERT INTO voice_binary_table(id,audioBinary) VALUES(?,?);";
			Object[] parims = new Object[2];
			
			parims[0] = new String(f.getName());
			parims[1] = dataArray;
			
			database.ExecSQL(insertSql, sb, parims);
			System.out.println("the tail is " + sb.toString());
			
			database.ExecSQL(insertSql);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		database.close(); 
        System.out.println("SaveBinary Successful!"); 
		
	}




	public byte[] read2list(File file) throws IOException {

		InputStream is = null;
		byte[] buf = null;
		int bufLen = 20000*1024;
		
		try {
			is = new BufferedInputStream(new FileInputStream(file));
			buf = new byte[bufLen];
			byte[] tmp = null;
			int len = 0;
			
			ArrayList data = new ArrayList(24);
			while ((len = is.read(buf, 0, bufLen)) != -1) {
				tmp = new byte[len];
				System.arraycopy(buf, 0, tmp, 0, len);
				data.add(tmp);
			}
			
			len = 0;
			if (data.size() == 1)
				return (byte[])data.get(0);
			for (int i = 0; i < data.size(); i++) {
				tmp = (byte[])data.get(i);
				System.arraycopy(tmp, 0, buf, len, tmp.length);
				
				len += tmp.length;
			}
			
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		}
		
		return buf;
	}

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics