0
\$\begingroup\$

I'm currently converting a Float32Array to an Int32Array for input to a real-time audio raw PCM to MP3 recording application.

new Int32Array([...new Float32Array(b)].map(f=>f<0?f*32768:f*32767)

The examples in the wild I've seen convert each float individually to avoid static, gaps, glitches when the audio recording is played back. I have a sense there is a way to do this without comparing each float, though I've seen no such examples in the wild for audio processing.

Looking at the I wonder is there a way to do this without comparing each float, basically, what is the shortest code to convert a Float32Array to a Int32Array or Int16Array for audio processing?

\$\endgroup\$
10
  • 2
    \$\begingroup\$ Note that in general Int32Array.from(new Float32Array(b), f => f * 32768) or some such is generally more efficient than round-tripping through an intermediate array. \$\endgroup\$
    – Neil
    Mar 9 at 20:37
  • \$\begingroup\$ @Neil 8**5 reduces by 1 character. \$\endgroup\$ Mar 9 at 21:37
  • \$\begingroup\$ @Neil We get glitches in the audio recording using either f*32768 or f*8**5. \$\endgroup\$ Mar 9 at 21:55
  • \$\begingroup\$ Sorry, I was just making a general efficiency comment, not a golfing suggestion. As such I just used a simple example. In particular I don't know what value range you're getting or what you're expected to map it to. \$\endgroup\$
    – Neil
    Mar 10 at 0:21
  • 2
    \$\begingroup\$ I found this blog post which shows how confusing this is. Out of those, I think the one used by PulseAudio seems to be the most straightforward. \$\endgroup\$
    – Neil
    Mar 10 at 9:25

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.