Created
February 7, 2026 21:53
-
-
Save Lamparter/0f7355bad5fdf9ca5e4e6eaf683c9407 to your computer and use it in GitHub Desktop.
Sine wave audio file powershell function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Function to generate a WAV file with a sine wave | |
| function New-SineWav { | |
| param( | |
| [string]$Path, | |
| [double]$DurationSec, | |
| [double[]]$Frequencies, # Single freq or array for sweep | |
| [int]$SampleRate = 44100 | |
| ) | |
| $samples = [int]($DurationSec * $SampleRate) | |
| $bytes = New-Object byte[] ($samples * 2) | |
| for ($i = 0; $i -lt $samples; $i++) { | |
| # If multiple frequencies, sweep across them | |
| if ($Frequencies.Count -gt 1) { | |
| $t = $i / $samples | |
| $freq = $Frequencies[0] + ($Frequencies[-1] - $Frequencies[0]) * $t | |
| } else { | |
| $freq = $Frequencies[0] | |
| } | |
| $value = [math]::Sin(2 * [math]::PI * $freq * ($i / $SampleRate)) | |
| $int16 = [int16]($value * 32767) | |
| $bytes[$i*2] = [byte]($int16 -band 0xFF) | |
| $bytes[$i*2+1] = [byte](($int16 -shr 8) -band 0xFF) | |
| } | |
| # WAV header | |
| $ms = New-Object System.IO.MemoryStream | |
| $bw = New-Object System.IO.BinaryWriter($ms) | |
| $bw.Write([System.Text.Encoding]::ASCII.GetBytes("RIFF")) | |
| $bw.Write([int]($bytes.Length + 36)) | |
| $bw.Write([System.Text.Encoding]::ASCII.GetBytes("WAVEfmt ")) | |
| $bw.Write([int]16) # PCM header size | |
| $bw.Write([short]1) # PCM format | |
| $bw.Write([short]1) # Mono | |
| $bw.Write([int]$SampleRate) | |
| $bw.Write([int]($SampleRate * 2)) # Byte rate | |
| $bw.Write([short]2) # Block align | |
| $bw.Write([short]16) # Bits per sample | |
| $bw.Write([System.Text.Encoding]::ASCII.GetBytes("data")) | |
| $bw.Write([int]$bytes.Length) | |
| $bw.Write($bytes) | |
| $bw.Flush() | |
| [System.IO.File]::WriteAllBytes($Path, $ms.ToArray()) | |
| $bw.Dispose() | |
| $ms.Dispose() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment