I want to get a list of installed MIDI Devices in Windows 10, using the Windows 10 UWP MIDI API.
This article shows example code to get a list of MIDI devices and their IDs, using C#:
using Windows.Devices.Midi;
using Windows.Devices.Enumeration;
...
private async void ListMidiDevices()
{
// Enumerate Input devices
var deviceList = DeviceInformation.FindAllAsync(
MidiInPort.GetDeviceSelector());
foreach (var deviceInfo in deviceList)
{
Console.WriteLine(deviceInfo.Id);
Console.WriteLine(deviceInfo.Name);
Console.WriteLine("----------");
}
// Output devices are enumerated the same way, but
// using MidiOutPort.GetDeviceSelector()
}
I tried inserting the code for ListMidiDevices in the Visual Studio Community 2015 "Hello World" example program. I put the code block in place of Console.WriteLine("Hello World!");
in the "hello world" console example. I added the "using" statements above in the proper place.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Devices.Midi;
using Windows.Devices.Enumeration;
namespace ConsoleApplicationHelloWorld
{
class Program
{
static void Main(string[] args)
{
// Enumerate Input devices
var deviceList = await DeviceInformation.FindAllAsync(
MidiInPort.GetDeviceSelector());
foreach (var deviceInfo in deviceList)
{
System.Diagnostics.Debug.WriteLine(deviceInfo.Id);
System.Diagnostics.Debug.WriteLine(deviceInfo.Name);
System.Diagnostics.Debug.WriteLine("----------");
}
// Output devices are enumerated the same way, but
// using MidiOutPort.GetDeviceSelector() }
}
}
Edit - VS wasn't building the UWP type. I upgraded to VS Community 2019, and installed ConsoleAppUniversal.vsix. Then I could create a new project - Console App C# Universal:
using System;
using Windows.Devices.Midi;
using Windows.Devices.Enumeration;
// This example code shows how you could implement the required main function for a
// Console UWP Application. You can replace all the code inside Main with your own custom code.
// You should also change the Alias value in the AppExecutionAlias Extension in the
// Package.appxmanifest to a value that you define. To edit this file manually, right-click
// it in Solution Explorer and select View Code, or open it with the XML Editor.
namespace ConsoleAppCsharpUniversal
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine("starting - no args");
// Enumerate Input devices
var deviceList = DeviceInformation.FindAllAsync(
MidiInPort.GetDeviceSelector());
foreach (var deviceInfo in deviceList)
{
Console.WriteLine(deviceInfo.Id);
Console.WriteLine(deviceInfo.Name);
Console.WriteLine("----------");
}
Console.WriteLine("finish - no args");
}
else
{
for (int i = 0; i < args.Length; i++)
{
Console.WriteLine($"arg[{i}] = {args[i]}");
}
}
Console.WriteLine("Press a key to continue: ");
Console.ReadLine();
}
}
}
Now the only remaining error is "foreach statement cannot operate on variables of type IAsyncOperation<DeviceInformationCollection> because IAsyncOperation<DeviceInformationCollection> does not contain a public instance definition for GetEnumerator"
Is there another way to access the device information without using an async method?
You have to make sure your project is targeting at least C# 7.1 (I think the template does have this out-of-the-box in VS 2019) and use the async Main method feature:
Your method signature will change to:
public static async Task Main(string[] args)
{
...
}
And then you need to await the FindAllAsync method:
var deviceList = await DeviceInformation.FindAllAsync(
MidiInPort.GetDeviceSelector());
Note: You can change the C# version by opening the csproj file in a text editor and adding the following into a <PropertyGroup>:
<LangVersion>7.1</LangVersion>
or even (if you want the latest features):
<LangVersion>latest</LangVersion>
Related
I'm trying to use the Text to Speech service on Microsoft azure and I used the official documentation and the official code using c# language but whenever I enter a value to let the program speak nothing happen not even an error message.
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Audio;
class Program
{
static string speechKey = "";
static string speechRegion = "";
static void OutputSpeechSynthesisResult(SpeechSynthesisResult speechSynthesisResult, string text)
{
switch (speechSynthesisResult.Reason)
{
case ResultReason.SynthesizingAudioCompleted:
Console.WriteLine($"Speech synthesized for text: [{text}]");
break;
case ResultReason.Canceled:
var cancellation = SpeechSynthesisCancellationDetails.FromResult(speechSynthesisResult);
Console.WriteLine($"CANCELED: Reason={cancellation.Reason}");
if (cancellation.Reason == CancellationReason.Error)
{
Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
Console.WriteLine($"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]");
Console.WriteLine($"CANCELED: Did you set the speech resource key and region values?");
}
break;
default:
break;
}
}
async static Task Main(string[] args)
{
var speechConfig = SpeechConfig.FromSubscription(speechKey, speechRegion);
// The language of the voice that speaks.
speechConfig.SpeechSynthesisVoiceName = "en-US-JennyNeural";
using (var speechSynthesizer = new SpeechSynthesizer(speechConfig))
{
// Get text from the console and synthesize to the default speaker.
Console.WriteLine("Enter some text that you want to speak >");
string text = Console.ReadLine();
var speechSynthesisResult = await speechSynthesizer.SpeakTextAsync(text);
OutputSpeechSynthesisResult(speechSynthesisResult, text);
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
whenever I run the app and I type anything nothing happens
here is the output image
I tried in my environment and got below results:
I executed the same code in my environment and got error:
Console:
Output:
The above error is ongoing issue with Microsoft azure in that they have mentioned the Speech SDK latest impacting the wide variety of TLS-dependent service use started failing. This error only occurs in Windows other API and MacOS has been working properly.
You can use this code get the (text to speech)
Code:
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Audio;
using System;
using System.Threading.Tasks;
namespace TextToSpeech
{
class Program
{
async static Task Main(string[] args)
{
await ProcessSpeech();
Console.WriteLine("Completed");
}
async static Task ProcessSpeech()
{
var l_speechConfig = SpeechConfig.FromEndpoint(new Uri("< endpoint>"), "key");
var l_audioConfig = AudioConfig.FromWavFileOutput("C:\\Users\\v-vsettu\\download1\\new1.wav");
var l_synthesizer = new SpeechSynthesizer(l_speechConfig, l_audioConfig);
await l_synthesizer.SpeakTextAsync("Hi siri");
}
}
}
Console:
File:
Please refer this MS-Q&A for ongoing problem in Speech-SDK for more information.
I facing some problems with the example I got from the ZeroMQ Guide, looks like the class ZSocket and ZContext doesn't exist.
I'm totally new with ZeroMQ (just start lo learn) and I'm following the "ØMQ - The Guide". The first example about REQ-REP, which is very simple, worked well. But now I'm trying something more similar to my objective, the "Brokerless Reliability (Freelance Pattern)" and this one didn't work.
I'm using Visual Studio 2019 with C# code, I created a new project, added NetMQ V4.0.1.6 via Nuget and copied the server code to my project. I got errors with ZContext and ZSocket. I already check the API V3 and API V4, they are clear different. The guide is totally based on version 3 and I'm using V 4. I didn't find any document about the changes or updates or equivalent function/classes/methods and I don't know how to convert the example to the NetMQ V4.
This is my test code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using NetMQ;
namespace Examples
{
static partial class Program
{
public static void FLServer1(string[] args)
{
//
// Freelance server - Model 1
// Trivial echo service
//
// Author: metadings
//
if (args == null || args.Length < 1)
{
Console.WriteLine();
Console.WriteLine("Usage: ./{0} FLServer1 [Endpoint]", AppDomain.CurrentDomain.FriendlyName);
Console.WriteLine();
Console.WriteLine(" Endpoint Where FLServer1 should bind on.");
Console.WriteLine(" Default is tcp://127.0.0.1:7780");
Console.WriteLine();
args = new string[] { "tcp://127.0.0.1:7780" };
}
using (var context = new ZContext())
using (var server = new ZSocket(context, ZSocketType.REP))
{
server.Bind(args[0]);
Console.WriteLine("I: echo service is ready at {0}", args[0]);
ZMessage message;
ZError error;
while (true)
{
if (null != (message = server.ReceiveMessage(out error)))
{
using (message)
{
server.Send(message);
}
}
else
{
if (error == ZError.ETERM)
return; // Interrupted
throw new ZException(error);
}
}
}
}
}
}
After long hours trying to understand that logic, I found a list of differences from ZeroMQ V3 and V4:
https://github.com/zeromq/netmq/wiki/Migrating-to-v4
Also, accidentally I found the example I was looking for:
https://github.com/NetMQ/Samples/tree/master/src/Brokerless%20Reliability%20(Freelance%20Pattern)/Model%20One
I'm trying to make a simple console app client (starter.exe) on c# .NET Framework 4.6 to make a WireGuard protocol based connection using Wireguard source code.
What is done:
Downloaded wireguard source code from here: git://git.zx2c4.com/wireguard-windows
Successfuly built Tunnel.dll in ..\embeddable-dll-service\amd64\tunnel.dll via build.bat
Created a project in Visual Studio 2015.using the c# code from ..\embeddable-dll-service\csharp
Starting from here some strange thing are happenning:
if launching starter.exe \service <path to *.conf> I receive the
error
Service run error: The service process could not connect to the
service controller.
if launching starter.exe without parameters everything works fine until I remove the if{} block:
Unhandled Exception: System.ComponentModel.Win32Exception: The service
did not respond to the start or control request in a timely fashion
at WireGuardTunnel.Service.Add(String configFile) in
D:\Depository\BitBucket\WireGuard_Tunnel_Repository\WireGuardTunnel_proj\Launcher\Service.cs:line
69 at WireGuardTunnel.Program.Main(String[] args) in
D:\Depository\BitBucket\WireGuard_Tunnel_Repository\WireGuardTunnel_proj\Launcher\Program.cs:line
83
That means even if the code in if{} block is not executed it influencese somehow the application behaviour.
Next, as I want to make my app work with parameters I solved the
issue by removing return afer Service.Run and passing args[1] to Service.Add(args[1]). It works OK, but I have an extra log line (the first one due to Service.Run perpetual error described above) in the log:
Service run error: The service process could not connect to the
service controller. 235660: [TUN] [chicago4] Watching network
interfaces 245661: [TUN] [chicago4] Resolving DNS names
245661: [TUN] [chicago4] Creating Wintun interface 225660: [TUN]
[chicago4] Starting WireGuard/0.3.1 (Windows 6.1.7601; amd64)
So finally the questions:
Why Service.Run(confFile) does not work
Why Service.Run(confFile) influences the Service.Add(confFile)
Why if{} block is executed when I launch starte.exe with no parameters
The original Program.cs without modification:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
namespace Tunnel
{
class Program
{
[DllImport("kernel32.dll")]
private static extern bool SetConsoleCtrlHandler(SetConsoleCtrlEventHandler handler, bool add);
private delegate bool SetConsoleCtrlEventHandler(UInt32 signal);
public static void Main(string[] args)
{
string baseDirectory = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
string configFile = Path.Combine(baseDirectory, "demobox.conf");
string logFile = Path.Combine(baseDirectory, "log.bin");
if (args.Length == 2 && args[0] == "/service")
{
configFile = args[1];
Service.Run(configFile);
return;
}
try { File.Delete(logFile); } catch { }
Ringlogger log = new Ringlogger(logFile, "GUI");
var logPrintingThread = new Thread(() =>
{
var cursor = Ringlogger.CursorAll;
while (Thread.CurrentThread.IsAlive)
{
var lines = log.FollowFromCursor(ref cursor);
foreach (var line in lines)
Console.WriteLine(line);
Thread.Sleep(300);
}
});
logPrintingThread.Start();
SetConsoleCtrlHandler(delegate
{
Service.Remove(configFile);
Environment.Exit(0);
return true;
}, true);
try
{
Service.Add(configFile);
logPrintingThread.Join();
}
finally
{
Service.Remove(configFile);
}
}
}
}
Bit late to the party but I was having the exact same issue as above and discovered that in order to get everything working correctly you have to have Tunnel.Service.Run("path to config") defined on application initialization either in your main loop or your constructor then you can run Tunnel.Service.Add("path to config", true) which will create the service and start the VPN connection. It's also good practice to destroy the service on close using Tunnel.Service.Remove("path to config", true) as the service will continue to run and you will still be connected to your VPN until it is stopped manually.
I am new in c#
I am trying to send command to USB port(usbport=========fx3(Cypress chip), to light on LED than with in the custom board))
I tried to scanport but it was failed because my computer(win10) recognized the usb as camera(fx3 is chip that image processing)
so i found this code in sysnet.pe.kr
using System;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
ListDevices().GetAwaiter().GetResult();
}
private static async Task ListDevices()
{
var devices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
foreach (var item in devices)
{
Console.WriteLine($"{item.Id}: {item.Name}");
devices.
}
}
}
}
it works!!! so I found port
but i don't have idea how to send command to the port!!!
please help me ㅠㅠ
First you must read your camera documentation (from producer website or .. , it may have programing sdk)
Otherwise you can use LibUsbDotNet
I developed a softphone for windows, I know how to register it as default tell application by reading this question, but I don`t know how get arguments sent from a web application or another win application while my softphone is running.
The standard code to call tell app from web app is something like this:
window.open("tel: 05525825");
If you have registered your application for the scheme tel: and the Command is "yourapp.exe %1", then you can read them from the commandline arguments as explained in How to access command line parameters outside of Main in C#:
string arguments = Environment.GetCommandLineArgs();
string phoneNumber = arguments[1];
Of course you need to do some sanity checking before bluntly accessing and using the array element.
If you setup the protocol URL keys correctly your application will be run with the data in the command line (E.g. args[] in main())
To pass data to an already running instance of your application the easiest way is to use the StartupNextInstance event provided by VisualBasic.ApplicationServices and re-process new incomming command lines:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Microsoft.VisualBasic.ApplicationServices;
namespace Foo
{
static class Program
{
[STAThread]
static void Main(string[] args)
{
var applicationBase = new ThisWindowsApplicationBase();
applicationBase.StartupNextInstance += (sender, e) => { applicationBase.HandleCommandLine(e.CommandLine); };
applicationBase.Run(args);
}
}
class ThisWindowsApplicationBase : WindowsFormsApplicationBase
{
internal ThisWindowsApplicationBase()
: base()
{
this.IsSingleInstance = true;
this.MainForm = new Form1();
this.HandleCommandLine(Environment.GetCommandLineArgs().Skip(1));
}
internal void HandleCommandLine(IEnumerable<string> commandLine)
{
this.MainForm.Text = "Processing: " + commandLine.FirstOrDefault();
}
}
}
Note this will not fire for the first run.