Sign in to follow this  
SirGorthon

[java] Strange mic input?? Am I doing this right?

Recommended Posts

SirGorthon    180
Howdy ya'll! I'm trying to get mic input as an array of bytes in PCM format (44100Hz, 16bit, 1 channel, signed, big-endian). However, the results are very funny! The first byte switches between 0 and -1. When the first byte is 0, the second byte (of the 16bit input) is between 0 and about 10 (usually 1 or 2ish), but when the first byte is -1, the second byte jumps to about 250. Am I not interpreting the bytes correctly? Relevant code:
	public void gameplayLoop()
	{	
		byte[] data = new byte[line.getBufferSize()/4];
		int numIntsRead = 0;
		int numBytesRead = 0;
		try
		{
	
			numBytesRead = line.read(data, 0, data.length);
			bytesToInts(data, numBytesRead);

		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	
	}

	public int[] bytesToInts(byte[] pdata, int num)
	{
		int[] data = new int[num/sampleSizeInBytes];
		for(int i = 0; i < num; i+=sampleSizeInBytes)
		{
			data[i/sampleSizeInBytes] = pdata[i];
			System.out.println(data[i/sampleSizeInBytes] + "\t" + (0x000000FF&pdata[i+1]));
		}
		return data;
	}
Example output: 0 0 -1 243 0 1 -1 249 0 1 -1 250 -1 254 -1 254 -1 246 0 4 I can also post the mic setup code, but the setup seems to be running fine in itself. I think the errors are on my part in attempting to read the data. Any help?

Share this post


Link to post
Share on other sites
greggles    347
You're not quite understanding how to convert the bytes to ints, correct? Those numbers that you gave us are (in the format that you stated) are the following:
0
-13
1
-7
1
-6
-2
-2
-10
4

So, they sound like they are just ambient noise (they don't seem to be very loud)?

Here, give this a try, it should be correct:


public int[] bytesToInts(byte[] pdata, int num)
{
int[] data = new int[num/2];
for(int i = 0; i < num; i+=2)
{
data[i/2] = (short)(((pdata[i] & 0xFF) << 8) | (pdata[i + 1] & 0xFF));//Yes, this is the easiest way! I'm converting the bits of two bytes to an unsigned big-endian short.

System.out.println(data[i/2]);
}
return data;
}

[/code]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this