DEV Community

Discussion on: Quick and dirty Audio playing in Golang on Windows

Collapse
 
kenjitamura profile image
kenjitamura

I'd also like to point out that the golang.org/x/sys/windows package includes a command mkwinsyscall that can do most of the work for you in creating a function that calls windows API's.

I created my own PlaySound library for this by creating a file with:

const (
    SND_APPLICATION uint = 0x80       //look for application specific association
    SND_ALIAS       uint = 0x10000    //system event alias in win.ini
    SND_ALIAS_ID    uint = 0x110000   //predefined identifier for system event alias
    SND_ASYNC       uint = 0x1        //play asynchronously and return immediately after begin
    SND_FILENAME    uint = 0x20000    //pszSound parameter is filename
    SND_LOOP        uint = 0x8        //play sound repeatedly until called again with pszSound set to null.  Must also set ASYNC
    SND_MEMORY      uint = 0x4        //pszSound points to sound in memory
    SND_NODEFAULT   uint = 0x2        //don't use default sound if target sound not found.  Returns silent
    SND_NOSTOP      uint = 0x10       //don't stop currently playing sounds if device in use.  Function returns false
    SND_RESOURCE    uint = 0x40004    //pszSound points to resource.  Need to set HMOD
    SND_SENTRY      uint = 0x00080000 //triggers a visual cue with sound.  Requires vista or later
    SND_SYNC        uint = 0x0        //sound is played synchronously and playsound returns after completes.  Default
    SND_SYSTEM      uint = 0x00200000 //sets the sound to be played with volume set for system notification sounds.  Requires vista or later
)

//go:generate go run golang.org/x/sys/windows/mkwinsyscall -output zsyscall_windows.go syscall_windows.go

//sys PlaySound(pszSound string, hmod *uint32, fdwSound uint) (ret bool) = Winmm.PlaySound
Enter fullscreen mode Exit fullscreen mode

Then after calling the command:

go generate syscall_windows.go
Enter fullscreen mode Exit fullscreen mode

A file called zsyscall_windows.go was generated that handles all the heavy lifting of translating the go values into windows values. An added benefit is that the generated file will follow sys/windows conventions like loading the dll library with windows.NewLazySystemDLL which limits the search path to the windows system path to help prevent dll preloading.