
Originally Posted by
grahamhughes
I never assume anything.
This code doesn't guarantee to fille the byte array with the contents of the file. This is a common mistake people make about the method InputStream.read(byte[]). It reads "some number of bytes" from the stream. You need to check the return value to see how many bytes were actually read.
Also, I suggest you close the file InputStream immediately after you've read the data into the byte array. Don't worry about closing the ByteArrayInputStream, and don't worry (for now) about closing the Player. So, get rid of the code that sleeps. When you've got it playing, used a PlayerListener to detect the end of the sound and close it then.
Graham.
ah, thanks for the tip about not all the bytes will be read. i didnt know that.
in any case, this is the code:
Code:
public void testAudio(){
try{
String path = "file:///E:/test.mp3";
FileConnection fileConnection = (FileConnection) Connector.open(path);
byte [] fileBytes = new byte[(int) fileConnection.fileSize()];
InputStream readStream = fileConnection.openInputStream();
String field1String = path;
int bytesRead = readStream.read(fileBytes);
readStream.close();
field1String += "\nRead " + bytesRead +" out of " + fileConnection.fileSize() + " bytes";
if(bytesRead == fileConnection.fileSize()){
field1String += "\nAll Read";
}
field1 = new TextField("test audio", field1String,1024, TextField.ANY);
ByteArrayInputStream inputStream = new ByteArrayInputStream(fileBytes);
Player player = Manager.createPlayer(inputStream, "audio/mp3");
player.realize();
VolumeControl vc = (VolumeControl) player.getControl("VolumeControl");
vc.setLevel(100);
player.prefetch();
player.start();
}catch(Exception e){
String exceptionString = e.toString();
e.printStackTrace();
field1 = new TextField("Exception", exceptionString,1024, TextField.ANY);
}
}
it shows in the TextField:
test audio
file:///E:/test.mp3
Read 4741833 out of 4741833 bytes
All Read
but there's no sound from the player.