我正在编写一个UWP应用程序,当耳机插入/拔出设备(PC或Mobile UWP)时,我需要收听耳机插头事件。
我试图处理MediaDevice::DefaultAudioRenderDeviceChanged
和Windows::Devices::Enumeration::DeviceWatcher
。
但它们都不能按预期工作。
我可以使用MediaDevice::DefaultAudioRenderDeviceChanged
处理默认的设备更改事件。但对于耳机插头外壳,默认设备不会改变。因此不会触发渲染设备更改事件。
Windows::Devices::Enumeration::DeviceWatcher
无法捕获该事件。
那么请帮助分享我如何在UWP中获得耳机插件事件?非常感谢。
答案 0 :(得分:0)
我曾尝试处理MediaDevice :: DefaultAudioRenderDeviceChanged和Windows :: Devices :: Enumeration :: DeviceWatcher。但它们都不能按预期工作。
您可以使用DeviceWatcher来处理DeviceWatcher.Added或DeviceWatcher.Removed个事件。
MainPage.xaml.cpp:
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="the.message" />
<property name="targetMethod" value="setMessage" />
<property name="arguments">
<list>
<value type="java.lang.String">This message was set in importing context file</value>
</list>
</property>
</bean>
MainPage.xaml中:
using namespace Windows::Devices::Enumeration;
using namespace Windows::UI::Core;
MainPage::MainPage()
{
InitializeComponent();
}
void DeviceWatcherCppSample::MainPage::btnClick_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
watcher=DeviceInformation::CreateWatcher(DeviceClass::AudioRender);
handlerAddedToken=watcher->Added += ref new Windows::Foundation::TypedEventHandler<DeviceWatcher ^, DeviceInformation ^>(this, &DeviceWatcherCppSample::MainPage::OnAdded);
handlerRemovedToken= watcher->Removed += ref new Windows::Foundation::TypedEventHandler<DeviceWatcher ^, DeviceInformationUpdate ^>(this, &DeviceWatcherCppSample::MainPage::OnRemoved);
handlerUpdatedToken= watcher->Updated += ref new Windows::Foundation::TypedEventHandler<Windows::Devices::Enumeration::DeviceWatcher ^, Windows::Devices::Enumeration::DeviceInformationUpdate ^>(this, &DeviceWatcherCppSample::MainPage::OnUpdated);
watcher->Start();
}
void DeviceWatcherCppSample::MainPage::OnAdded(DeviceWatcher ^sender, DeviceInformation ^args)
{
this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this, args]()
{
tbResult->Text = args->Name +"is Added";
}));
}
void DeviceWatcherCppSample::MainPage::OnRemoved(DeviceWatcher ^sender, DeviceInformationUpdate ^args)
{
this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this, args]()
{
tbResult->Text = args->Id + "is Removed";
}));
}
void DeviceWatcherCppSample::MainPage::OnUpdated(Windows::Devices::Enumeration::DeviceWatcher ^sender, Windows::Devices::Enumeration::DeviceInformationUpdate ^args)
{
this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this, args]()
{
tbResult->Text = args->Id + "is Updated";
}));
}
这是完整的演示:DeviceWatcherSample。您也可以参考Official Sample的方案2。