# Loqu8 iCE sound check, version 2. # What it does: lists your audio outputs, renders a short Chinese phrase with each # Chinese voice installed on this PC (into memory), then plays three short sounds # through the same Windows audio route iCE uses: a tone, a second tone, and one # spoken Chinese phrase. It writes the results to loqu8-sound-check.txt on your # Desktop. It sends nothing anywhere and changes no settings. $ErrorActionPreference = 'Continue' $out = New-Object System.Collections.Generic.List[string] function Say($s) { $out.Add($s); Write-Output $s } Add-Type -TypeDefinition @' using System; using System.Runtime.InteropServices; public static class L8Audio { [StructLayout(LayoutKind.Sequential)] public struct WAVEFORMATEX { public ushort wFormatTag, nChannels; public uint nSamplesPerSec, nAvgBytesPerSec; public ushort nBlockAlign, wBitsPerSample, cbSize; } [StructLayout(LayoutKind.Sequential)] public struct WAVEHDR { public IntPtr lpData; public uint dwBufferLength, dwBytesRecorded; public IntPtr dwUser; public uint dwFlags, dwLoops; public IntPtr lpNext; public IntPtr reserved; } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct WAVEOUTCAPS { public ushort wMid, wPid; public uint vDriverVersion; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public string szPname; public uint dwFormats; public ushort wChannels, wReserved1; public uint dwSupport; } [DllImport("winmm.dll")] static extern uint waveOutOpen(out IntPtr h, uint dev, ref WAVEFORMATEX f, IntPtr cb, IntPtr inst, uint flags); [DllImport("winmm.dll")] static extern uint waveOutPrepareHeader(IntPtr h, IntPtr hdr, uint sz); [DllImport("winmm.dll")] static extern uint waveOutWrite(IntPtr h, IntPtr hdr, uint sz); [DllImport("winmm.dll")] static extern uint waveOutUnprepareHeader(IntPtr h, IntPtr hdr, uint sz); [DllImport("winmm.dll")] static extern uint waveOutReset(IntPtr h); [DllImport("winmm.dll")] static extern uint waveOutClose(IntPtr h); [DllImport("winmm.dll")] public static extern uint waveOutGetNumDevs(); [DllImport("winmm.dll", CharSet=CharSet.Unicode)] static extern uint waveOutGetDevCapsW(UIntPtr id, ref WAVEOUTCAPS c, uint sz); public static string DevName(uint i) { var c = new WAVEOUTCAPS(); uint r = waveOutGetDevCapsW((UIntPtr)i, ref c, (uint)Marshal.SizeOf(typeof(WAVEOUTCAPS))); return r == 0 ? c.szPname : ("error " + r); } [ComImport, Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface IMMDeviceEnumerator { [PreserveSig] int EnumAudioEndpoints(int flow, int mask, out IntPtr col); [PreserveSig] int GetDefaultAudioEndpoint(int flow, int role, out IMMDevice dev); } [ComImport, Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface IMMDevice { [PreserveSig] int Activate(ref Guid iid, int ctx, IntPtr p, out IntPtr o); [PreserveSig] int OpenPropertyStore(int access, out IntPtr ps); [PreserveSig] int GetId([MarshalAs(UnmanagedType.LPWStr)] out string id); } [ComImport, Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")] class MMDeviceEnumerator { } public static string DefaultId(int role) { try { var e = (IMMDeviceEnumerator)(new MMDeviceEnumerator()); IMMDevice d; int hr = e.GetDefaultAudioEndpoint(0, role, out d); if (hr != 0) return "none (0x" + hr.ToString("X") + ")"; string id; d.GetId(out id); return id; } catch (Exception ex) { return "error: " + ex.Message; } } // Plays 16-bit PCM through WAVE_MAPPER (the default output), as iCE does, // and reports every step's result code and how long playback ran. public static string Play(byte[] pcm, int rate, int ch, int timeoutMs) { var f = new WAVEFORMATEX { wFormatTag = 1, nChannels = (ushort)ch, nSamplesPerSec = (uint)rate, wBitsPerSample = 16 }; f.nBlockAlign = (ushort)(ch * 2); f.nAvgBytesPerSec = (uint)(rate * f.nBlockAlign); var sw = System.Diagnostics.Stopwatch.StartNew(); IntPtr h; uint r = waveOutOpen(out h, 0xFFFFFFFF, ref f, IntPtr.Zero, IntPtr.Zero, 0); string log = "open=" + r + " (" + sw.ElapsedMilliseconds + " ms)"; if (r != 0) return log + " => FAILED TO OPEN THE OUTPUT"; IntPtr data = Marshal.AllocHGlobal(pcm.Length); Marshal.Copy(pcm, 0, data, pcm.Length); var hdr = new WAVEHDR { lpData = data, dwBufferLength = (uint)pcm.Length }; int hs = Marshal.SizeOf(typeof(WAVEHDR)); IntPtr ph = Marshal.AllocHGlobal(hs); Marshal.StructureToPtr(hdr, ph, false); string verdict = ""; r = waveOutPrepareHeader(h, ph, (uint)hs); log += "; prepare=" + r; if (r != 0) verdict = " => FAILED TO PREPARE"; else { long t0 = sw.ElapsedMilliseconds; r = waveOutWrite(h, ph, (uint)hs); log += "; write=" + r; if (r != 0) verdict = " => FAILED TO WRITE"; else { bool done = false; long ms = 0; while (sw.ElapsedMilliseconds - t0 < timeoutMs) { var cur = (WAVEHDR)Marshal.PtrToStructure(ph, typeof(WAVEHDR)); if ((cur.dwFlags & 1) != 0) { done = true; break; } System.Threading.Thread.Sleep(5); } ms = sw.ElapsedMilliseconds - t0; long clipMs = (long)pcm.Length * 1000 / f.nAvgBytesPerSec; log += "; ran " + ms + " ms for a " + clipMs + " ms clip"; if (!done) { waveOutReset(h); verdict = " => STUCK (never finished)"; } else if (ms < clipMs / 2) verdict = " => FINISHED TOO SOON (the output took the sound but did not play it)"; else verdict = " => played"; } waveOutUnprepareHeader(h, ph, (uint)hs); } waveOutClose(h); Marshal.FreeHGlobal(ph); Marshal.FreeHGlobal(data); return log + verdict; } } '@ function EndpointName($id) { if ($id -notmatch '\{[^}]+\}$') { return $id } $guid = $Matches[0] $k = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Render\$guid\Properties" try { $p = Get-ItemProperty -Path $k -ErrorAction Stop $desc = $p.'{a45c254e-df1c-4efd-8020-67d146a850e0},2' $iface = $p.'{b3f8fa53-0004-438e-9003-51a46e139bfc},6' $bt = $p.PSObject.Properties | Where-Object { "$($_.Value)" -match 'BTHENUM|BTHHFENUM|Bluetooth' } | Select-Object -First 1 $tag = if ($bt) { ' [Bluetooth]' } else { '' } return "$desc ($iface)$tag" } catch { return $id } } function Tone($rate, $hz, $ms) { $n = [int]($rate * $ms / 1000); $b = New-Object byte[] ($n * 2) for ($i = 0; $i -lt $n; $i++) { $env = [Math]::Min(1.0, [Math]::Min($i, $n - $i) / ($rate * 0.01)) $s = [int16](9000 * $env * [Math]::Sin(2 * [Math]::PI * $hz * $i / $rate)) $b[2*$i] = [byte]($s -band 0xFF); $b[2*$i+1] = [byte](($s -shr 8) -band 0xFF) } return ,$b } $os = Get-CimInstance Win32_OperatingSystem Say "Loqu8 iCE sound check v6, $(Get-Date -Format 'yyyy-MM-dd HH:mm')" Say "Windows: $($os.Caption) $($os.Version) build $([Environment]::OSVersion.Version.Build)" Say "" Say "1. Audio outputs" $d0 = [L8Audio]::DefaultId(0); $d2 = [L8Audio]::DefaultId(2) Say " Default output (the one iCE uses): $(EndpointName $d0)" Say " Default for calls: $(EndpointName $d2)" Say " Active outputs:" foreach ($k in Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Render') { try { if ((Get-ItemProperty $k.PSPath -ErrorAction Stop).DeviceState -eq 1) { Say " - $(EndpointName ('x' + $k.PSChildName))" } } catch { } } if ((EndpointName $d0) -match '\[Bluetooth\]') { Say " NOTE: the default output is a Bluetooth device." } Say "" Say "2. Chinese voices through the older speech engine (SAPI), rendered into memory, not played" Say " The newer OneCore voices often cannot be used this way; that is normal, and iCE 9.38.9 and later speaks them through the newer engine (2b)." $text = -join ([char[]](0x4F60,0x597D,0x4E16,0x754C)) $cats = @('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices', 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech_OneCore\Voices') $tags = @{1='PCM'; 3='float'; 65534='extensible'} $clip = $null; $clipVoice = ''; $clipRate = 0 foreach ($c in $cats) { $kind = if ($c -like '*OneCore*') { 'OneCore' } else { 'SAPI' } $cat = New-Object -ComObject SAPI.SpObjectTokenCategory try { $cat.SetId($c, $false) } catch { Say " [$kind] cannot open the voice list: $($_.Exception.Message)"; continue } $toks = $cat.EnumerateTokens() for ($i = 0; $i -lt $toks.Count; $i++) { $t = $toks.Item($i); $lang = "$($t.GetAttribute('Language'))" if ($lang -notmatch '(^|;)(804|404|c04|1004|1404)($|;)') { continue } $name = $t.GetDescription(); $line = " [$kind] $name`: " try { $v = New-Object -ComObject SAPI.SpVoice try { $v.Voice = $t } catch { $line += "COULD NOT SELECT ($($_.Exception.Message)); " } $used = $v.Voice.GetDescription() $ms = New-Object -ComObject SAPI.SpMemoryStream $ms.Format.Type = 22 $v.AllowAudioOutputFormatChangesOnNextSet = $true $v.AudioOutputStream = $ms $sw = [Diagnostics.Stopwatch]::StartNew(); [void]$v.Speak($text, 0); $sw.Stop() $wfx = $ms.Format.GetWaveFormatEx(); [byte[]]$b = $ms.GetData(); $bits = $wfx.BitsPerSample $peak = 0.0 if ($bits -eq 16 -and $b.Length -ge 2) { for ($k = 0; $k -lt $b.Length - 1; $k += 2) { $s = [Math]::Abs([int][BitConverter]::ToInt16($b, $k)); if ($s -gt $peak) { $peak = $s } }; $peak = $peak / 32768.0 } $durMs = [int](1000.0 * $b.Length / [Math]::Max(1, $wfx.AvgBytesPerSec)) $tag = $tags[[int]$wfx.FormatTag]; if (-not $tag) { $tag = "format $($wfx.FormatTag)" } $verdict = if ($used -ne $name -and $kind -eq 'OneCore') { "the older engine spoke $used instead (normal; see 2b)" } elseif ($used -ne $name) { "WRONG VOICE SPOKE ($used)" } elseif ($bits -ne 16) { 'NOT 16-BIT (iCE would refuse it)' } elseif ($b.Length -eq 0) { 'NO AUDIO' } elseif ($peak -lt 0.02) { 'SILENT' } else { 'OK' } $line += "$tag $($wfx.SamplesPerSec) Hz $bits-bit $($wfx.Channels)ch, $durMs ms, peak $([Math]::Round($peak,2)), $($sw.ElapsedMilliseconds) ms to render => $verdict" if (-not $clip -and $verdict -eq 'OK' -and $lang -match '804') { $clip = $b; $clipVoice = $name; $clipRate = [int]$wfx.SamplesPerSec } } catch { if ($kind -eq 'OneCore') { $line += "not usable by the older engine ($($_.Exception.Message)); normal, see 2b" } else { $line += "FAILED: $($_.Exception.Message)" } } Say $line } } Say "" Say "2b. What Windows' speech APIs list, and the newer speech path" try { Add-Type -AssemblyName System.Speech $inst = (New-Object System.Speech.Synthesis.SpeechSynthesizer).GetInstalledVoices() | Where-Object { $_.VoiceInfo.Culture.Name -like 'zh*' } Say " Desktop voices (.NET GetInstalledVoices): $((@($inst) | ForEach-Object { $_.VoiceInfo.Name + ' enabled=' + $_.Enabled }) -join '; ')" } catch { Say " Desktop voices: could not list ($($_.Exception.Message))" } # The newer (WinRT) speech path is reachable only from Windows PowerShell 5.1. # Under PowerShell 7 this part runs in a Windows PowerShell child process # (the same code, passed inline; nothing is downloaded). $winrt = @' $ProgressPreference = 'SilentlyContinue' $text = -join ([char[]](0x4F60,0x597D,0x4E16,0x754C)) try { Add-Type -AssemblyName System.Runtime.WindowsRuntime $asTask = [System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object { $_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and $_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1' } | Select-Object -First 1 [void][Windows.Media.SpeechSynthesis.SpeechSynthesizer,Windows.Media,ContentType=WindowsRuntime] $all = [Windows.Media.SpeechSynthesis.SpeechSynthesizer]::AllVoices | Where-Object { $_.Language -like 'zh*' } " OneCore voices (WinRT AllVoices): $((@($all) | ForEach-Object { $_.DisplayName + ' (' + $_.Language + ')' }) -join '; ')" foreach ($v in $all) { $line = " [WinRT] $($v.DisplayName): " try { $ws = New-Object Windows.Media.SpeechSynthesis.SpeechSynthesizer $ws.Voice = $v $op = $ws.SynthesizeTextToStreamAsync($text) $task = $asTask.MakeGenericMethod([Windows.Media.SpeechSynthesis.SpeechSynthesisStream]).Invoke($null, @($op)) if (-not $task.Wait(10000)) { $line += 'TIMEOUT' } else { $line += "rendered $($task.Result.Size) bytes => OK" } } catch { $line += "FAILED: $($_.Exception.InnerException.Message) $($_.Exception.Message)" } $line } } catch { " OneCore voices: could not list ($($_.Exception.Message))" } '@ if ($PSVersionTable.PSVersion.Major -ge 6) { Say " (PowerShell $($PSVersionTable.PSVersion): this part runs in Windows PowerShell)" $enc = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($winrt)) $ps51 = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe' foreach ($l in (& $ps51 -NoProfile -NonInteractive -ExecutionPolicy Bypass -OutputFormat Text -EncodedCommand $enc 2>$null)) { Say $l } } else { foreach ($l in (Invoke-Expression $winrt)) { Say $l } } Say "" Say "2c. Voice lists in the registry (read only)" $regLists = @( @{ Name = 'older list (SAPI)'; Path = 'HKLM:\SOFTWARE\Microsoft\Speech\Voices\Tokens' }, @{ Name = 'newer list (OneCore)'; Path = 'HKLM:\SOFTWARE\Microsoft\Speech_OneCore\Voices\Tokens' } ) $seen = @{} foreach ($l in $regLists) { try { $rows = Get-ChildItem -Path $l.Path -ErrorAction Stop | ForEach-Object { $lang = '' try { $lang = (Get-ItemProperty -Path (Join-Path $_.PSPath 'Attributes') -ErrorAction Stop).Language } catch { } if ($lang -match '(^|;)(804|404|c04|1004|1404)($|;)') { $_.PSChildName } } $seen[$l.Name] = @($rows) Say " $($l.Name): $((@($rows)) -join ', ')" } catch { Say " $($l.Name): could not read ($($_.Exception.Message))" } } $older = @($seen['older list (SAPI)']); $newer = @($seen['newer list (OneCore)']) $copies = @($older | Where-Object { $newer -contains $_ }) if ($copies.Count -gt 0) { Say " NOTE: the older list also holds these newer voices (likely copied there): $($copies -join ', ')" } Say "" Say "3. Playing through iCE's audio route (listen for three sounds)" Say " a) a low tone, iCE's Windows-voice format (22050 Hz): $([L8Audio]::Play((Tone 22050 440 700), 22050, 1, 3000))" Start-Sleep -Milliseconds 400 Say " b) a higher tone, Kokoro's format (24000 Hz): $([L8Audio]::Play((Tone 24000 660 700), 24000, 1, 3000))" Start-Sleep -Milliseconds 400 if ($clip) { Say " c) Chinese spoken by $clipVoice ($clipRate Hz): $([L8Audio]::Play($clip, $clipRate, 1, 5000))" } else { Say " c) no Mandarin voice rendered, so no spoken phrase was played" } Say "" Say "Please tell us which of the three sounds (a, b, c) you heard." $path = Join-Path ([Environment]::GetFolderPath('Desktop')) 'loqu8-sound-check.txt' try { ($out + @('', '----------------------------------------', '')) | Out-File -FilePath $path -Encoding utf8 -Append; Write-Output ""; Write-Output "Added to $path" } catch { Write-Output "Could not save the file: $($_.Exception.Message)" }