go-wca icon indicating copy to clipboard operation
go-wca copied to clipboard

Add API to set default audio output device

Open ThiefMaster opened this issue 3 years ago • 4 comments

There is an undocumented COM API called IPolicyConfig which allows to do nice things like changing the default audio device used by Windows. An example tool (which works fine) can be found e.g. here: https://github.com/DanStevens/AudioEndPointController/tree/master/EndPointController

Is there any chance you could add those APIs to this library as well?

ThiefMaster avatar Jan 31 '21 12:01 ThiefMaster

This works fine for me - just leaving it here in case someone else wants to use it :)

package main

import (
	"syscall"
	"unsafe"

	"github.com/go-ole/go-ole"
	"github.com/moutend/go-wca/pkg/wca"
)

type IPolicyConfigVista struct {
	ole.IUnknown
}

type IPolicyConfigVistaVtbl struct {
	ole.IUnknownVtbl
	GetMixFormat          uintptr
	GetDeviceFormat       uintptr
	SetDeviceFormat       uintptr
	GetProcessingPeriod   uintptr
	SetProcessingPeriod   uintptr
	GetShareMode          uintptr
	SetShareMode          uintptr
	GetPropertyValue      uintptr
	SetPropertyValue      uintptr
	SetDefaultEndpoint    uintptr
	SetEndpointVisibility uintptr
}

func (v *IPolicyConfigVista) VTable() *IPolicyConfigVistaVtbl {
	return (*IPolicyConfigVistaVtbl)(unsafe.Pointer(v.RawVTable))
}

func (v *IPolicyConfigVista) SetDefaultEndpoint(deviceID string, eRole wca.ERole) (err error) {
	err = pcvSetDefaultEndpoint(v, deviceID, eRole)
	return
}

func pcvSetDefaultEndpoint(pcv *IPolicyConfigVista, deviceID string, eRole wca.ERole) (err error) {
	var ptr *uint16
	if ptr, err = syscall.UTF16PtrFromString(deviceID); err != nil {
		return
	}
	hr, _, _ := syscall.Syscall(
		pcv.VTable().SetDefaultEndpoint,
		3,
		uintptr(unsafe.Pointer(pcv)),
		uintptr(unsafe.Pointer(ptr)),
		uintptr(uint32(eRole)))
	if hr != 0 {
		err = ole.NewError(hr)
	}
	return
}

ThiefMaster avatar Jan 31 '21 19:01 ThiefMaster

Thanks, just implemented this and its working on my end as well

Silenc3IsGold3n avatar Feb 13 '21 02:02 Silenc3IsGold3n