user1508284
user1508284

Reputation: 71

playing Audio from BLOB field of a Table of a SQLite DB

I store my audio file to a sqlite database (as BLOB) and now I want to gain it from db and also play it when a button clicked. my db table has three field: rowID, image, audio that in each row of my table, an image and an audio stored (as BLOB).

I try this but did not work for me:

byte[] byteAudio2 = null;

Cursor cur1 = db.query("audiofromdb_tbl", null, null, null, null, null, null);

cur1.moveToFirst();
byteAudio2 = cur1.getBlob(cur1.getColumnIndex("audio"));        
File tempWav = null;
    FileOutputStream fos = new FileOutputStream(tempWav);
    fos.write(byteAudio2);
fos.close();

MediaPlayer mp = new MediaPlayer();
mp.setDataSource(fos.getFD());
mp.prepare();
mp.start();

Upvotes: 4

Views: 2226

Answers (2)

JJeset BC
JJeset BC

Reputation: 23

Perhaps too late but if someone needs it.

This works for me:

 File file;
 FileOutputStream fos;

 byteaudio = cursor.getBlob(cursor.getColumnIndex("sonido"));

 try {

        file = File.createTempFile("sound", "sound");
        fos = new FileOutputStream(file);
        fos.write(byteaudio);
        fos.close();

        Log.d("File", file.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }
mp = MediaPlayer.create(getActivity(), Uri.fromFile(file));
            mp.start();

Upvotes: 1

user1786387
user1786387

Reputation: 11

try something like this :

byte[] buffer = new byte[2048];
int size = 0;
ByteArrayInputStream byteArrayStream = new ByteArrayInputStream(byteAudio2); 

while ((size = byteArrayStream.read(buffer, 0, buffer.length)) > 0) {
    fos.write(buffer, 0, size);
}

[]

Upvotes: 1

Related Questions