2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PowerShellでサウンド再生

Posted at

wavファイルの再生

Media.SoundPlayer

fig1.ps1
$player = New-Object Media.SoundPlayer "C:\Windows\Media\tada.wav"
$player.Play()

Windows API

fig2.ps1
$SND_SYNC = 0x0000
$cscode = @"
[DllImport("winmm.dll")]
public static extern bool sndPlaySoundA(string lpszSound, UInt32 fuSound);
"@
$winapi = Add-Type -Name "hoge" -MemberDefinition $cscode -PassThru
$winapi::sndPlaySoundA("C:\Windows\Media\tada.wav", $SND_SYNC)

メモリの再生

wavファイルのイメージをメモリに作成し再生する。

Media.SoundPlayer

fig3.ps1
function fourcc($s) { return [Text.Encoding]::ASCII.GetBytes($s) }
function word([UInt16] $x) { return [BitConverter]::GetBytes($x) }
function dword([Uint32] $x) { return [BitConverter]::GetBytes($x) }

[Byte[]] $b = @()
$b += fourcc("RIFF")
$b += dword(36 + 4000)
$b += fourcc("WAVE")
$b += fourcc("fmt ")
$b += dword(16)
$b += word(1)
$b += word(1)
$b += dword(8000)
$b += dword(8000)
$b += word(1)
$b += word(8)
$b += fourcc("data")
$b += dword(4000)
$b += @(0x90,0x90,0x70,0x70) * 500
$b += @(0x90,0x90,0x90,0x90,0x70,0x70,0x70,0x70) * 250
# [IO.File]::WriteAllBytes("pipo.wav", $b)

$ms = [IO.MemoryStream]::new($b)
$player = [Media.SoundPlayer]::new($ms)
$player.Play()

Windows API

sndPlaySoundAの第1引数の型はLPCTSTR。
ファイル名の場合はstringだけどメモリを渡す場合はByte[]とする。

fig4.ps1
$SND_SYNC = 0x0000
$SND_MEMORY = 0x0004
$cscode = @"
[DllImport("winmm.dll")]
public static extern bool sndPlaySoundA(Byte[] lpszSound, UInt32 fuSound);
"@
$winapi = Add-Type -Name "hoge" -MemberDefinition $cscode -PassThru

function fourcc($s) { return [Text.Encoding]::ASCII.GetBytes($s) }
function word([UInt16] $x) { return [BitConverter]::GetBytes($x) }
function dword([Uint32] $x) { return [BitConverter]::GetBytes($x) }

[Byte[]] $b = @()
$b += fourcc("RIFF")
$b += dword(36 + 4000)
$b += fourcc("WAVE")
$b += fourcc("fmt ")
$b += dword(16)
$b += word(1)
$b += word(1)
$b += dword(8000)
$b += dword(8000)
$b += word(1)
$b += word(8)
$b += fourcc("data")
$b += dword(4000)
$b += @(0x90,0x90,0x70,0x70) * 500
$b += @(0x90,0x90,0x90,0x90,0x70,0x70,0x70,0x70) * 250
# [IO.File]::WriteAllBytes("pipo.wav", $b)

$winapi::sndPlaySoundA($b, $SND_MEMORY -bor $SND_SYNC)
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?