# Sound.extract() \> ByteArray \> WAV file?

**URL:** <https://forum.kirupa.com/t/sound-extract-bytearray-wav-file/299849>\
**Category:** flash\
**Created:** [November 11, 2009, 9:24pm UTC](https://forum.kirupa.com/t/sound-extract-bytearray-wav-file/299849 "2009-11-11T21:24:42Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![doonaboon](https://avatars.discourse-cdn.com/v4/letter/d/b782af/32.png) [@doonaboon](https://forum.kirupa.com/u/doonaboon)\
**Post date:** [November 11, 2009, 9:24pm UTC](https://forum.kirupa.com/t/sound-extract-bytearray-wav-file/299849/1 "2009-11-11T21:24:42Z")

</div>

Hi,

I’m having some trouble getting the following code to work - trying to use the new Sound.extract() function to get two seconds of a Sound into a ByteArray, and then create a new bytearray with a WAV header, and then output the file. The resulting ‘test.wav’ file sounds very wrong although slightly recognisable? I think I may have some of the WAV header settings may be wrong but I’m not quite sure what’s the matter and after a long time scratching my head I need help! Any suggestions would be much appreciated!

Thanks,  
Dan

```auto

var snd:Sound = new TestSound();

var sndBytes:ByteArray = new ByteArray();
sndBytes.endian = Endian.LITTLE_ENDIAN;

snd.extract( sndBytes, 44100 * 2 );

var wav:ByteArray = encode( sndBytes );

var f:FileReference = new FileReference();
f.save( wav, "test.wav" );

function encode( data:ByteArray ):ByteArray{
    var channels:uint = 2;
    var bits:uint = 16;
    var rate:uint = 44100;
    
    var bytes: ByteArray = new ByteArray();
    bytes.endian = Endian.LITTLE_ENDIAN;
    
    bytes.writeUTFBytes( 'RIFF' );
    bytes.writeInt( uint( data.length + 44 ) );
    bytes.writeUTFBytes( 'WAVE' );
    bytes.writeUTFBytes( 'fmt ' );
    bytes.writeInt( uint( 16 ) );
    bytes.writeShort( uint( 1 ) );
    bytes.writeShort( channels );
    bytes.writeInt( rate );
    bytes.writeInt( uint( rate * channels * ( bits / 8 ) ) );
    bytes.writeShort( uint( channels * ( bits / 8 ) ) );
    bytes.writeShort( bits );
    bytes.writeUTFBytes( 'data' );
    bytes.writeInt( data.length );
    bytes.writeBytes( data );
    bytes.position = 0;

    return bytes;
}

```
