Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
Developer
Posts: 239
Registered: ‎07-26-2010
My Device: Z10
My Carrier: Telkomsel

InputStream.read(buffer) returns -1?

[ Edited ]

I'd like to decrypt an MP3 (encrypted using TEA algorithm) on the fly while playing it.

So my idea was decrypt the file chunks by chunks and play them.

 

byte[] buffer = new byte[1024];

public void play(String path){
	try {
		FileConnection fc = (FileConnection) Connector.open(path,	Connector.READ);
		InputStream is = fc.openInputStream();
		int len;
						
		while ((len = is.read(buffer)) != -1){
			playEncryptedAudio(buffer);
		}
			
		is.close();
		fc.close();
	}
	catch (IOException ioex){
				
	}
}
	
// TEA implementation: http://www.winterwell.com/software/TEA.php
private void playEncryptedAudio(byte[] data) throws IOException {
	TEA tea = new TEA("ABCDE ABCDE ABC A ABCDEF".getBytes());
	byte[] decrypted_data = tea.decrypt(data);
	ByteArrayInputStream stream = new ByteArrayInputStream(decrypted_data);
	ByteArrayInputStreamDataSource source = new ByteArrayInputStreamDataSource(stream, "audio/mpeg");

	try {
		player = Manager.createPlayer(source);
		player.start();
	}
	catch (MediaException me){

	}
}

 When I ran the code on simulator, I didn't hear anything. Later I found that the cause was is.read(buffer) = -1. Thus, the song wasn't played at all. How to fix this?

Developer
Posts: 19,636
Registered: ‎07-14-2008
My Device: Not Specified

Re: InputStream.read(buffer) returns -1?

I suggest you try and get your code working with a non encrypted file before you start trying to decrypt on the fly.

 

In this case your:

is.read(buffer)

code is just reading the file from the FileConnection and as I am sure you are aware, the -1 means End of File.  So I think you need to check you data.  

 

Hope this helps. 

Developer
Posts: 239
Registered: ‎07-26-2010
My Device: Z10
My Carrier: Telkomsel

Re: InputStream.read(buffer) returns -1?

[ Edited ]

Previously I used this:

public void play(String path){
	try {
		FileConnection fc = (FileConnection) Connector.open(path,	Connector.READ);
		InputStream is = fc.openInputStream();
		byte[] rawData = IOUtilities.streamToBytes(is);
						
		playEncryptedAudio(rawData);
			
		is.close();
		fc.close();
	}
	catch (IOException ioex){
				
	}
}

It worked. Kinda slow, though.

So the problem is not the file itself, but how to read it properly.

Developer
Posts: 239
Registered: ‎07-26-2010
My Device: Z10
My Carrier: Telkomsel

Re: InputStream.read(buffer) returns -1?

I think this is kinda weird.

After I cleaned the simulator, is.read(buffer) returns the buffer size.

 

Example:

If i use private byte[] buffer = new byte[128]; then is.read(buffer) will return 128.

Now I'm facing an ArrayIndexOutOfBoundsException, which occured in the decryption part.