Search code examples
androiddoubleshort

How can I convert a short[] to double[]?


Now, I'm working one audio signal processing, and I want to do a real time display audio sound wave which I recorded by my phone.

Here is a problem that my audio format is "ENCODING_PCM_16BIT". So how can I change 16bit short data to double format ?

here is my code, but it's work not properly. Can anyone help me fix this?

try {

        AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, Sample_rate, Channel, Encording,
                Buffersize);

        DataOutputStream dos = new DataOutputStream(
                new BufferedOutputStream(new FileOutputStream(MainActivity.file)));

        short[] buffer = new short[Buffersize / 2]; //870 double/ 2 = 435 double
        System.out.println("The buffer size is " + Buffersize);
        timer1();
        audioRecord.startRecording(); // Start record
        while (MainActivity.isrecord) {
            int bufferReadResult = audioRecord.read(buffer, 0, buffer.length);
            System.out.println("The buffer size is " + bufferReadResult);
            for (int i = 0; i < bufferReadResult/2; i++) {
                dos.writeShort(buffer[i]);
                **tempraw[i] = (double)buffer[i];**
            }
            phase = DataProcess(tempraw);
        }
        audioRecord.stop(); // record stop
        audioRecord.release();
        audioRecord = null;
        dos.close(); // Output stream close
        dos = null;
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

I want to put those data at "short[] buffer" to "double[] tempraw"

Thanks !

After I look some code from internet, I made this. I think it's worked, just pretty slow, 2ms for one double

private static double shorttodouble(short[] a, int index) {
    // TODO Auto-generated method stub
    long l;
    l = a[index + 0];
    l &= 0xffff;
    l |= ((long) a[index + 1] << 16);
    l &= 0xffffffffl;
    l |= ((long) a[index + 2] << 32);
    l &= 0xffffffffffffl; 
    l |= ((long) a[index + 3] << 48);
    l &= 0xffffffffffffffffl; 
    l |= ((long) a[index + 4] << 64);
    return (double)l;
}

Solution

  • Try this :---

     short[] buffer = new short[size];
        double[] transformed = new double[buffer.length];
        for (int j=0;j<buffer.length;j++) {
        transformed[j] = (double)buffer[j];
        }