Powershell Auto Mute, when headphones are accidently unplugged.


INTRODUCTION:

Do you know mobile phones have an inbuilt feature to Auto mute a playing song/music,  if by mistake you plug out your earphones from the jack, that prevents your phone to keep playing the music on speakers, which could be quite embarrassing in some surroundings and situations, but unfortunately we don’t have such a feature available on our desktops/laptops 😦

And I was victim of such an embarrassing situation a few days back, when I was listening to some music on my developer workstation in my office with my headphones on and tried to rest my head on the chair’s backrest in relaxing position, due to tension the cable got unplugged from headphone jack and allowed the music to be played for a while from my laptop speakers and it took me few seconds to realize that I screwed it and everybody in the office is  looking at me 😀 . Somehow in hurry I managed to mute my PC. Phew!

It was embarrassing but the good part was I was at least not listening to Taylor Swift 😛 , So I thought why not to look for a solution available to fix this for me? Really I didn’t care much about finding one but was more interested in making one with Powershell! 🙂

THE IDEA:

  1. Run a background PowerShell script (Hidden preferred) always when your machine is up
  2. That monitors a device plug – IN/OUT events
  3. If a Device Plug OFF event is triggered, make sure to MUTE your machine
  4. Or, in the case of Plug-IN event is generated UNMUTE the machine.

MAKING IT WORK:

  • Running the script in background:  We can create a basic Task in Windows task scheduler to run a PowerShell script whenever machine whenever computer starts to run a PowerShell script1This will make sure our script is always running in the background, waiting for a device to be plugged In/out
  • Capture Device Plug-In/Out Events:  After some googling and research I found a WMI class Win32_DeviceChangeEvent that represents device change/modification events on a windows machine. Here  is the link to MSDN Documentation of the WMI class.It clearly mentions that, Event Type 3 generated under this class is Device Removed and Event Type 2 is Device arrival (plugged in).2

    After knowing this I  believe, now it’s easier to register a WMI event using Powershell cmdlet

    Register-WMIEvent

    and wait for any of the above events (Event Type 2 or 3) to occur using cmdlet

    Wait-Event

    3

  • Handling the events: In the case  Event type 3 is triggered, which as per Microsoft’s documentation means – A device plugged off (Removal) event, then we should MUTE our Machine, and when the device is plugged in (Arrival) event is generated we need to UNMUTE the machine.3.
  • NOTE: We need to access Audio API on our Windows machine, for which we’ve to add some C# code in our script. * Source

SCRIPT:

Wrapping up everything in a PowerShell script looks something like this

[cmdletbinding()]
Param()
#Adding definitions for accessing the Audio API
Add-Type -TypeDefinition @'
using System.Runtime.InteropServices;
[Guid("5CDF2C82-841E-4546-9722-0CF74078229A"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IAudioEndpointVolume {
// f(), g(), ... are unused COM method slots. Define these if you care
int f(); int g(); int h(); int i();
int SetMasterVolumeLevelScalar(float fLevel, System.Guid pguidEventContext);
int j();
int GetMasterVolumeLevelScalar(out float pfLevel);
int k(); int l(); int m(); int n();
int SetMute([MarshalAs(UnmanagedType.Bool)] bool bMute, System.Guid pguidEventContext);
int GetMute(out bool pbMute);
}
[Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IMMDevice {
int Activate(ref System.Guid id, int clsCtx, int activationParams, out IAudioEndpointVolume aev);
}
[Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IMMDeviceEnumerator {
int f(); // Unused
int GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice endpoint);
}
[ComImport, Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")] class MMDeviceEnumeratorComObject { }
public class Audio {
static IAudioEndpointVolume Vol() {
var enumerator = new MMDeviceEnumeratorComObject() as IMMDeviceEnumerator;
IMMDevice dev = null;
Marshal.ThrowExceptionForHR(enumerator.GetDefaultAudioEndpoint(/*eRender*/ 0, /*eMultimedia*/ 1, out dev));
IAudioEndpointVolume epv = null;
var epvid = typeof(IAudioEndpointVolume).GUID;
Marshal.ThrowExceptionForHR(dev.Activate(ref epvid, /*CLSCTX_ALL*/ 23, 0, out epv));
return epv;
}
public static float Volume {
get {float v = -1; Marshal.ThrowExceptionForHR(Vol().GetMasterVolumeLevelScalar(out v)); return v;}
set {Marshal.ThrowExceptionForHR(Vol().SetMasterVolumeLevelScalar(value, System.Guid.Empty));}
}
public static bool Mute {
get { bool mute; Marshal.ThrowExceptionForHR(Vol().GetMute(out mute)); return mute; }
set { Marshal.ThrowExceptionForHR(Vol().SetMute(value, System.Guid.Empty)); }
}
}
'@ -Verbose
While($true)
{
#Clean all events in the current session since its in a infinite loop, to make a fresh start when loop begins
Get-Event | Remove-Event -ErrorAction SilentlyContinue
#Registering the Event and Waiting for event to be triggered
Register-WmiEvent -Class Win32_DeviceChangeEvent
Wait-Event -OutVariable Event |Out-Null
$EventType = $Event.sourceargs.newevent | `
Sort-Object TIME_CREATED -Descending | `
Select-Object EventType -ExpandProperty EventType -First 1
#Conditional logic to handle, When to Mute/unMute the machine using Audio API
If($EventType -eq 3)
{
[Audio]::Mute = $true
Write-Verbose "Muted [$((Get-Date).tostring())]"
}
elseif($EventType -eq 2 -and [Audio]::Mute -eq $true)
{
[Audio]::Mute = $false
Write-Verbose "UnMuted [$((Get-Date).tostring())]"
}
}
view raw PSAutoMute.ps1 hosted with ❤ by GitHub

You can also fork my Github repo of the script here and feel free to contribute 🙂

HOW TO RUN:

You can run the script on demand like in the below animation or you can create a task in task scheduler to make it run (Hidden) always when your machine starts.

gif

Hope you’ll find the script useful or at least gain some knowledge. Thanks for reading, Cheers! 🙂

signature

31 thoughts on “Powershell Auto Mute, when headphones are accidently unplugged.

  1. I find it odd that this isn’t something for this in windows settings already. I have ubuntu dual booted on my machine and noticed that this functionality was on by default.

    Like

  2. […] This is something that mobile phones do i.e., when you unplug your headphones, the music stops automatically. The logic behind this is that you’re either done listening to music or you’ve accidentally removed your headphones and you need a quick way to turn it off. The script was basically written on that same principle by Prateek Singh of GEEKEEFY. […]

    Like

  3. […] C’est quelque chose que font les téléphones mobiles intelligents, c’est-à-dire qu’au moment où vous débranchez les écouteurs, la musique s’arrête automatiquement. La logique derrière cela est que vous avez fini d’écouter de la musique ou que vous avez accidentellement retiré vos écouteurs et que vous avez besoin d’un moyen rapide de les éteindre. Essentiellement, le script a été écrit exactement sur le même principe par « Prateek Singh » par GEEKEEFY. […]

    Like

  4. […] Dies ist etwas, was Mobiltelefone tun, dh wenn Sie Ihre Kopfhörer abziehen, stoppt die Musik automatisch. Die Logik dahinter ist, dass Sie entweder mit dem Musikhören fertig sind oder versehentlich Ihre Kopfhörer entfernt haben und eine schnelle Möglichkeit benötigen, sie auszuschalten. Das Drehbuch wurde im Grunde nach dem gleichen Prinzip von geschrieben Prateek Singh von GEEKEEFY. […]

    Like

  5. […] Este ceva ce fac telefoanele mobile și anume, când deconectați căștile, muzica se oprește automat. Logica din spatele acestui lucru este că fie ați terminat de ascultat muzică, fie v-ați scos din greșeală căștile și aveți nevoie de o modalitate rapidă de a le opri. Scenariul a fost în principiu scris pe același principiu de către Prateek Singh de la GEEKEEFY. […]

    Like

  6. […] Isso é algo que os telefones celulares fazem, ou seja, quando você desconecta os fones de ouvido, a música para automaticamente. A lógica por trás disso é que você terminou de ouvir música ou removeu acidentalmente seus fones de ouvido e precisa de uma maneira rápida de desligá-los. O roteiro foi basicamente escrito nesse mesmo princípio por Prateek Singh do GEEKEEFY. […]

    Like

  7. […] Αυτό είναι κάτι που κάνουν τα κινητά τηλέφωνα, δηλαδή, όταν αποσυνδέετε τα ακουστικά σας, η μουσική σταματά αυτόματα. Η λογική πίσω από αυτό είναι ότι είτε έχετε τελειώσει με την ακρόαση μουσικής είτε έχετε αφαιρέσει κατά λάθος τα ακουστικά σας και χρειάζεστε έναν γρήγορο τρόπο για να τα απενεργοποιήσετε. Το σενάριο γράφτηκε βασικά με την ίδια αρχή από Prateek Singh του GEEKEEFY. […]

    Like

  8. […] Tas ir kaut kas, ko dara mobilie tālruņi, ti, kad atvienojat austiņas, mūzika tiek automātiski apturēta. Šī loģika ir tāda, ka esat vai nu pabeidzis klausīties mūziku, vai arī esat nejauši izņēmis austiņas, un jums ir nepieciešams ātrs veids, kā tās izslēgt. Skriptu pamatā rakstīja pēc tāda paša principa Prateks Sings no GEEKEEFY. […]

    Like

  9. […] Ini adalah sesuatu yang ponsel lakukan yaitu, ketika Anda mencabut headphone Anda, musik berhenti secara otomatis. Logika di balik ini adalah Anda sudah selesai mendengarkan musik atau Anda tidak sengaja melepas headphone dan Anda perlu cara cepat untuk mematikannya. Naskahnya pada dasarnya ditulis dengan prinsip yang sama oleh Prateek Singh dari GEEKEEFY. […]

    Like

  10. […] Це те, що роблять мобільні телефони, тобто коли ви відключаєте навушники, музика автоматично припиняється. Логіка цього полягає в тому, що ви або закінчили слухати музику, або випадково зняли навушники, і вам потрібен швидкий спосіб їх вимкнути. Сценарій був в основному написаний за таким же принципом Пратік Сінгх із GEEKEEFY. […]

    Like

  11. […] これは携帯電話が行うことです。つまり、ヘッドホンを抜くと、音楽が自動的に停止します。 この背後にある論理は、あなたが音楽を聴き終えたか、誤ってヘッドフォンを取り外したため、それをオフにする簡単な方法が必要であるということです。 スクリプトは基本的に同じ原則に基づいて書かれました GEEKEEFYのPrateekSingh。 […]

    Like

  12. […] То је нешто што мобилни телефони раде, тј. када искључите слушалице, музика аутоматски престаје. Логика иза овога је да сте или завршили са слушањем музике или сте случајно уклонили слушалице и потребан вам је брз начин да их искључите. Сценарио је у основи написан на истом принципу од Пратик Синг из ГЕЕКЕЕФИ. […]

    Like

  13. […] Dit is iets dat mobiele telefoons doen, dat wil zeggen, wanneer u uw hoofdtelefoon loskoppelt, stopt de muziek automatisch. De logica hierachter is dat je ofwel klaar bent met het luisteren naar muziek of dat je per ongeluk je koptelefoon hebt verwijderd en een snelle manier nodig hebt om hem uit te zetten. Het script is in feite op hetzelfde principe geschreven door Prateek Singh van GEEKEEFY. […]

    Like

  14. […] Гэта тое, што робяць мабільныя тэлефоны, напрыклад, калі вы адключаеце навушнікі, музыка спыняецца аўтаматычна. Логіка гэтага заключаецца ў тым, што вы альбо скончылі слухаць музыку, альбо выпадкова знялі навушнікі, і вам патрэбен хуткі спосаб іх адключэння. Сцэнар быў у асноўным напісаны па такім жа прынцыпе Працік Сінгх з GEEKEEFY. […]

    Like

  15. […] Det er noget, mobiltelefoner gør, dvs. at når du trækker dine høretelefoner ud, stopper musikken automatisk. Logikken bag dette er, at du enten er færdig med at lytte til musik, eller også har du ved et uheld fjernet dine hovedtelefoner, og du har brug for en hurtig måde at slukke dem på. Manuskriptet blev grundlæggende skrevet efter det samme princip af Prateek Singh fra GEEKEEFY. […]

    Like

  16. […] هذا شيء تفعله الهواتف المحمولة ، على سبيل المثال ، عندما تقوم بفصل سماعات الرأس ، تتوقف الموسيقى تلقائيًا. المنطق وراء ذلك هو أنك إما أنهيت الاستماع إلى الموسيقى أو أنك قمت بإزالة سماعات الرأس بطريق الخطأ وتحتاج إلى طريقة سريعة لإيقاف تشغيلها. تمت كتابة النص بشكل أساسي على نفس المبدأ بواسطة براتيك سينغ من GEEKEEFY. […]

    Like

  17. […] Đây là điều mà điện thoại di động làm, tức là khi bạn rút tai nghe ra, nhạc sẽ tự động dừng. Logic đằng sau điều này là bạn đã nghe nhạc xong hoặc bạn đã vô tình tháo tai nghe của mình và bạn cần một cách nhanh chóng để tắt nó đi. Về cơ bản, kịch bản được viết trên nguyên tắc đó bởi Prateek Singh của GEEKEEFY. […]

    Like

Leave a comment