in reply to Win32::Sound 16 bit example

Yikes, When i try and unpack the 16bit sound value right after i pack it, i get a value which is incorrect if the initial value is less than zero. Basically, the unpack("v",...) is not working correctly. Any advice would be appreciated. I want to unpack the value so i can use it when i read in sound. I use this code only to illustrate. This program outputs two different numbers if the initial value of v is below zero. I need it to output the same numbers so i know i am reading the sound file correctly.
use Win32::Sound; # Create the object my $WAV = new Win32::Sound::WaveOut(44100, 16, 1); my $data = ""; my $counter = 0; my $increment = 440/44100; # Generate 44100 samples ( = 1 second) for my $i (1..44100) { # Calculate the pitch # (range 0..65335 for 16 bits) $v = int(sin($counter/2*3.14) * (65335/2)); #signed integer (v) range -32768 <-> 32767 print "$v = ".unpack("v",pack("v", $v))."\n"; $data .= pack("v", $v); $counter += $increment; } $WAV->Load($data); # get it $WAV->Write(); # hear it 1 until $WAV->Status(); # wait for completion $WAV->Save("16.wav"); # write to disk $WAV->Unload(); # drop it exit;
thanks to all for help and for reading.
jtrue

Replies are listed 'Best First'.
Re: Unpacking 16bit sound
by BrowserUk (Patriarch) on Jul 22, 2005 at 20:20 UTC

    The 'v' is unsigned 16-bit little-endian. It works fine for packing signed 16-bit values to little-endian, but not for unpacking them.

    To recover the signed value use:

    print unpack 's', pack 'v', -32767;; -32767

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
    "Science is about questioning the status quo. Questioning authority".
    The "good enough" maybe good enough for the now, and perfection maybe unobtainable, but that should not preclude us from striving for perfection, when time, circumstance or desire allow.