1

while streaming music i'm getting pcm data as type short[] and i want to save it to file in my android device so i can play it again later (using AudioTrack). i wan't the store of the music to be efficent in memory and cpu.

how to save short[] to file cause i dont see any function in.write(short[])?

how can i decrease the space\cpu for saving this file?

Marek Sebera
  • 39,650
  • 37
  • 158
  • 244
gilush14
  • 485
  • 1
  • 9
  • 20

2 Answers2

3

Wrap your FileOutputStream with DataOutputStream:

DataOutputStream doStream = new DataOutputStream(new BufferedOutputStream(fileOutputStream));
doStream.writeInt(numberArray.length); //Save size
for (int i=0;i<numberArray.length;i++) {
    doStream.writeShort(numberArray[i]); //Save each number
}

Same way for reading it back:

DataInputStream diStream = new DataInputStream(new BufferedInputStream(fileInputStream));
int size = diStream.readInt(); //Read size
short[] data = new short[size]; //Create new array with required length
for (int i=0;i<size;i++) {
    data[i] = diStream.readShort(); //Read each number
}
bezmax
  • 25,562
  • 10
  • 53
  • 84
0

Without any encoding to MP3 or similar you can always do like this.

short[] sound = ...;
ByteBuffer byteMyShorts = ByteBuffer.allocate(sound.length * 2);
ShortBuffer shortBytes = byteMyShorts.asShortBuffer();
shortBytes.put(sound);
byteMyShorts.flip();

// byteMyShorts.array() now contains your short[] array as an
// array of bytes.
Jens
  • 16,853
  • 4
  • 55
  • 52