Is there a way to find out whether a microphone/recording device is currently being used by an application in Windows?
I am aware that by using NAudio one can easily get a list of all recording devices as follows:
public void getAudioDevices()
{
DeviceNameByID = new Dictionary<string, string>();
var enumerator = new NAudio.CoreAudioApi.MMDeviceEnumerator();
// Allows you to enumerate rendering devices in certain states
var endpoints = enumerator.EnumerateAudioEndPoints(
DataFlow.Capture,
DeviceState.Active);
foreach (var endpoint in endpoints)
{
float volumeLevel = endpoint.AudioEndpointVolume.MasterVolumeLevelScalar;
Debug.WriteLine($"Volume: {volumeLevel}");
DeviceNameByID[endpoint.ID] = endpoint.DeviceFriendlyName;
Debug.WriteLine($"{endpoint.ID}: {endpoint.DeviceFriendlyName} - {endpoint.State}");
}
NotificationClient nClient = new NotificationClient();
// Aswell as hook to the actual event
enumerator.RegisterEndpointNotificationCallback(nClient);
}
but I am not sure as to how/if one can get any knowledge on their current usage.
Related
I'm fairly new to C#. In my program, I can measure the masterpeek value of the computer. But what I need right now is only the masterpeek value of a particular application, rather than the masterpeek value of the computer. For example chrome.exe masterpeek value.
I'm importing audio output devices into ComboBox.
var deviceEnum = new MMDeviceEnumerator();
var devices = deviceEnum.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active);
foreach (var dev in devices)
{
comboDevices.Items.Add(dev.FriendlyName);
}
comboDevices.SelectedIndex = 0;
deviceEnum.Dispose();
I choose the output device.
using (MMDeviceEnumerator deviceEnum = new MMDeviceEnumerator())
{
var deviceList = deviceEnum.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active).ToList();
device = deviceList[comboDevices.SelectedIndex];
}
I can show the masterpeek value with the progressbar.
if (comboDevices.SelectedItem != null)
{
var mpValue = Math.Round(device.AudioMeterInformation.MasterPeakValue * 100);
progressAudioMeter.Value = Convert.ToInt32(mpValue);
}
But now what I want to do exactly is the volume value of a particular application instead of the total volume value. For example chrome.exe
An example image from the audio mixer
I did some research and couldn't find exactly what I wanted. Can you help me? I don't know how I can do this.
VLC GUI shows the list of available webcams, like v4l2:///dev/video0 and v4l2:///dev/video1, I am wondering is there a way to get a list of available webcams? what about their default resolution?
I tried this but md.MediaList is empty.
var mds = libVlc.MediaDiscoverers(MediaDiscovererCategory.Devices);
if (mds.Any(x => x.LongName == "Video capture"))
{
var devices = mds.First(x => x.LongName == "Video capture");
var md = new MediaDiscoverer(libVlc, devices.Name);
foreach (var media1 in md.MediaList)
{
// Nothing ...
}
}
Your MediaDiscoverer is empty because you never call md.Start().
For more info, I found this really helpful: /LibVLCSharp/MediaDiscoverer.cs
That being said, I had no success using MediaDiscoverer to look for webcams myself.
If you don't insist on using LibVLC, you can list all camera devices without any third party software: How can I get a list of camera devices from my PC C#
from Francesco Bonizzi:
public static List<string> GetAllConnectedCameras()
{
var cameraNames = new List<string>();
using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE (PNPClass = 'Image' OR PNPClass = 'Camera')"))
{
foreach (var device in searcher.Get())
{
cameraNames.Add(device["Caption"].ToString());
}
}
return cameraNames;
}
I was trying to print to an usb printer using usbmanager, the App can detect the printer device but when i run it doesnt print. there are no errors and all passing data is ok.
Printer : Bixolon SRP 275III
Type: USB
private async void printReciept()
{
UsbManager m_usbManager;
m_usbManager = (UsbManager)Application.Context.GetSystemService(Context.UsbService);
var deviceList = m_usbManager.DeviceList;
IEnumerable<UsbDevice> deviceIterator = deviceList.Values.AsEnumerable();
UsbDevice m_usbdevice = null;
if (deviceIterator.Count() > 0)
{
var device = deviceIterator.ElementAt(0);
m_usbdevice = device;
string ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
var mPermissionIntent = PendingIntent.GetBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
m_usbManager.RequestPermission(m_usbdevice, mPermissionIntent);
UsbDeviceConnection deviceConnection = null;
try
{
using (var usbInterface = m_usbdevice.GetInterface(0))
{
using (var usbEndpoint = usbInterface.GetEndpoint(0))
{
mEndPoint = usbEndpoint;
deviceConnection = m_usbManager.OpenDevice(m_usbdevice);
byte[] bytesHello = Encoding.UTF8.GetBytes("Hello");
deviceConnection.BulkTransfer(usbEndpoint, bytesHello, bytesHello.Length, 0);
}
}
}
catch
{
}
}
}
You are sending the string to be printed directly to the bulk endpoint, or actually you are doing bulk transfer to the first endpoint found without knowing any of it's characteristics? I think it is a bit more complex than that.
First try to find out whether your printer supports USB printing class or some proprietary implementation. You can do this easily e.g. by connecting the printer to Windows PC and looking from the device manager, usbdeview or some other similar application.
If it supports printing class, read this document and implement your driver based on that (or use the one you may already have in Android). If it only supports proprietary implementation, you need to get the specifications for it or do some reverse engineering.
You may need to learn about PCL which may also be needed.
I am attempting to write code that reads each item from the user's Windows Media Player library. This code works for the majority of users, but for some users, getAll() will return an empty list when they clearly have hundreds or thousands of items in their Windows Media Player library.
var player = new WindowsMediaPlayer();
var collection = player.mediaCollection;
var list = collection.getAll();
int total = list.count;
I am referencing the WMPLib namespace by adding a COM reference to wmp.dll. My application ships with Interop.WMPLib.dll. How would some users' machines be configured in such a way that they run Windows Media Player with many songs in their library, but WMPLib fails to function correctly? Furthermore, what workarounds exist to reliably read the user's Windows Media Player library in all cases?
Try this snippet and see if it works for you.
public List<MusicEntry> GetMusicLibrary()
{
List<MusicEntry> entries;
IWMPPlaylist mediaList = null;
IWMPMedia mediaItem;
try
{
// get the full audio media list
mediaList = media.getByAttribute("MediaType", "Audio");
entries = new List<MusicEntry>(mediaList.count);
for (int i = 0; i < mediaList.count; i++)
{
mediaItem = mediaList.get_Item(i);
// create the new entry and populate its properties
entry = new MusicEntry()
{
Title = GetTitle(mediaItem),
Album = GetAlbum(mediaItem),
Artist = GetArtist(mediaItem),
TrackNumber = GetTrackNumber(mediaItem),
Rating = GetRating(mediaItem),
FileType = GetFileType(mediaItem)
};
entries.Add(entry);
}
}
finally
{
// make sure we clean up as this is COM
if (mediaList != null)
{
mediaList.clear();
}
}
return entries;
}
For more information refer to this excellent article on Code Project.
http://www.codeproject.com/Articles/36338/Export-Windows-Media-Player-Music-Metadata-to-XML
I searched around on Google for this, but the only things I came up with were outdated and did not work.
Does anyone have any information on how to get joystick data using C# .NET?
Since this was the top hit I got on google while researching joystick / gamepad input in C#, I thought I should post a response for others to see.
The easiest way I found was to use SharpDX and DirectInput. You can install it via NuGet (SharpDX.DirectInput)
After that, it's simply a matter of calling a few methods:
Sample code from SharpDX
static void Main()
{
// Initialize DirectInput
var directInput = new DirectInput();
// Find a Joystick Guid
var joystickGuid = Guid.Empty;
foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad,
DeviceEnumerationFlags.AllDevices))
joystickGuid = deviceInstance.InstanceGuid;
// If Gamepad not found, look for a Joystick
if (joystickGuid == Guid.Empty)
foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick,
DeviceEnumerationFlags.AllDevices))
joystickGuid = deviceInstance.InstanceGuid;
// If Joystick not found, throws an error
if (joystickGuid == Guid.Empty)
{
Console.WriteLine("No joystick/Gamepad found.");
Console.ReadKey();
Environment.Exit(1);
}
// Instantiate the joystick
var joystick = new Joystick(directInput, joystickGuid);
Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid);
// Query all suported ForceFeedback effects
var allEffects = joystick.GetEffects();
foreach (var effectInfo in allEffects)
Console.WriteLine("Effect available {0}", effectInfo.Name);
// Set BufferSize in order to use buffered data.
joystick.Properties.BufferSize = 128;
// Acquire the joystick
joystick.Acquire();
// Poll events from joystick
while (true)
{
joystick.Poll();
var datas = joystick.GetBufferedData();
foreach (var state in datas)
Console.WriteLine(state);
}
}
I hope this helps.
I even got this to work with a DualShock3 and the MotioninJoy drivers.
One: use SlimDX.
Two: it looks something like this (where GamepadDevice is my own wrapper, and the code is slimmed down to just the relevant parts).
Find the joystick / pad GUIDs:
public virtual IList<GamepadDevice> Available()
{
IList<GamepadDevice> result = new List<GamepadDevice>();
DirectInput dinput = new DirectInput();
foreach (DeviceInstance di in dinput.GetDevices(DeviceClass.GameController, DeviceEnumerationFlags.AttachedOnly))
{
GamepadDevice dev = new GamepadDevice();
dev.Guid = di.InstanceGuid;
dev.Name = di.InstanceName;
result.Add(dev);
}
return result;
}
Once the user has selected from the list, acquire the gamepad:
private void acquire(System.Windows.Forms.Form parent)
{
DirectInput dinput = new DirectInput();
pad = new Joystick(dinput, this.Device.Guid);
foreach (DeviceObjectInstance doi in pad.GetObjects(ObjectDeviceType.Axis))
{
pad.GetObjectPropertiesById((int)doi.ObjectType).SetRange(-5000, 5000);
}
pad.Properties.AxisMode = DeviceAxisMode.Absolute;
pad.SetCooperativeLevel(parent, (CooperativeLevel.Nonexclusive | CooperativeLevel.Background));
pad.Acquire();
}
Polling the pad looks like this:
JoystickState state = new JoystickState();
if (pad.Poll().IsFailure)
{
result.Disconnect = true;
return result;
}
if (pad.GetCurrentState(ref state).IsFailure)
{
result.Disconnect = true;
return result;
}
result.X = state.X / 5000.0f;
result.Y = state.Y / 5000.0f;
int ispressed = 0;
bool[] buttons = state.GetButtons();
The bad news is that Microsoft seems to stop supporting their NET libraries for DirectX and focus on XNA instead. I don't work in GameDev so I don't need to use XNA but you may try it if you developing computer games. The good news is that there are other approaches. One is SlimDX the new framework to help you to wok with DirectX from C#. The other way is to directly add references of "Microsoft.DirectX.dll" and "Microsoft.DirectX.DirectInput.dll" to your project. you can find them "..\Windows\Microsoft.NET\DirectX for Managed Code\". if you you are going to use last approach here is a link to codeproject where you can read how to work with a joystick.
EDIT:
If your application is based on NET version newer then 2.0 the application may hang on. To fix this problem change config file and add this:
<startup useLegacyV2RuntimeActivationPolicy="true">
Google led me here and while not a requirement of this question, OpenTK is a good option for Windows and Linux (under mono) support.
From the OpenTK docs, this code works on Raspberry Pi + Raspbian + Mono 3.12.0:
for (int i = 0; i < 4; i++)
{
var state = Joystick.GetState(i);
if (state.IsConnected)
{
float x = state.GetAxis(JoystickAxis.Axis0);
float y = state.GetAxis(JoystickAxis.Axis1);
// Print the current state of the joystick
Console.WriteLine(state);
}
}
This question is old, but it seems to be active even to this day, so I'm posting anyway.
If you need to get input from XInput only, take a look at XInputium. This is a .NET library that is specialized in XInput controllers. It is pretty straightforward, and has many code samples you can look at.