Skip to content

Instantly share code, notes, and snippets.

@philhartung
Last active June 9, 2021 21:56
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save philhartung/a6e45da9dfa0e00bdc7c7b1f2b9b2f08 to your computer and use it in GitHub Desktop.
Generate sine wave audio and output it to default audiodevice
const { RtAudio, RtAudioFormat } = require('audify');
const rtAudio = new RtAudio();
// constants
const samplerate = 48000;
const ffp = 48;
// audio device
let audioOutput = {
deviceId: rtAudio.getDefaultOutputDevice(),
nChannels: 2,
firstChannel: 0
};
// Open the input/output stream
rtAudio.openStream(audioOutput, null, RtAudioFormat.RTAUDIO_SINT16, samplerate, ffp, 'Sine');
// Start the stream
rtAudio.start();
let pcm = Buffer.alloc(ffp * 2 * 2);
let index = 0;
let freq = 440;
// 50 ms buffering (silence)
for(let i = 0; i < 50; i++){
rtAudio.write(pcm);
}
rtAudio.setFrameOutputCallback(function(){
rtAudio.write(pcm);
// generate sine wave buffer
for(let i = 0; i < ffp; i++){
let sine = 32767 * Math.sin(2 * freq * Math.PI * index/samplerate);
pcm.writeInt16LE(sine, 4*i);
pcm.writeInt16LE(sine, 4*i + 2);
index = (index + 1) % (samplerate + 1);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment