如何監測耳機/麥克風設備插拔操作


沒事的時候想起來做這么個功能,主要是想在插入耳機之后能自動調節到較小的音量,免得耳朵被震得難受。

在搜索過程中先搜到了CSDN論壇的一篇帖子《C#監測音頻設備熱插拔功能》(http://bbs.csdn.net/topics/390502788)

雖然沒有靠這篇帖子解決問題,但是帖子還是指出了道路,就是用Windows Vista之后提供的新Core Audio API來偵測

在這里我是用NAudio(http://naudio.codeplex.com/)這個開源庫中CoreAudio的實現

然后在搜索英文資源的時候注意用“jack detection”關鍵字

微軟論壇上的這篇討論很有幫助:http://social.msdn.microsoft.com/Forums/windowsdesktop/zh-CN/610aacff-062e-4453-8437-01f0de038b07/jack-detection-for-headset?forum=windowspro-audiodevelopment

最終最完整的解答是在這里:http://stackoverflow.com/questions/6163119/handling-changed-audio-device-event-in-c-sharp

 

雖然完整的代碼寫好了,但是還是花了一兩天時間來讓代碼能正確運行,因為能否偵測到插拔操作,和硬件及驅動也有關系

最開始在插拔的時候只有OnPropertyValueChanged事件可以正常觸發,其他事件毫無反應,一度讓我以為代碼哪里出了問題,直到讀了MSDN里面的這段話,才讓我把重心移到硬件及驅動上來,這段話是這樣的:

Unlike the connection between an adapter and an external bus such as USB or the IEEE 1394 bus, the connection between an endpoint device and an adapter device does not support PnP device detection. However, some audio adapters support jack-presence detection: when a plug is inserted into or removed from a jack, the hardware generates an interrupt to notify the adapter driver of the change in the hardware configuration. The endpoint manager in Windows Vista can exploit this hardware capability to notify applications which endpoint devices are present at any time. In this way, the operation of the endpoint manager is analogous to that of the Plug and Play manager, which keeps track of the adapter devices that are present in the system.

我測試的環境使用的聲卡都是Realtek的,我仔細研究了控制面板里面的音頻管理器的設置項目,注意到了紅框選項,修改了之后終於可以偵測到麥克風的插拔了。

但是耳機的插拔還是不行,我在筆記本和台式機上反復測試,終於在台式機上可以偵測到音頻輸入/耳機/麥克風三個插孔的插拔操作了,不過在筆記本上還是不行,即便是我在筆記本上安裝了最新的Realtek聲卡驅動,我個人認為區別應該在硬件上,也許筆記本上的聲卡在功能上有某種程度的縮水或者設計的妥協導致。

下面附上一些圖以供回憶吧:

筆記本:

台式機:

程序的輸出:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM