Example VU Meter using Windows Media Graph API? - c#

The question says it all.
I would like to create the simplest possible VU-meter example, using the new UWP Media Graph API, but so far, I haven't found any good examples.
There are a couple of questions in this:
I am using the "normal" code to enumerate my microphones:
var deviceInformation = await DeviceInformation.FindAllAsync(MediaDevice.GetAudioCaptureSelector());
However, when I create an AudioGraphSettings object, I cannot find a property to pass the device found. There is a property named DesiredRenderDeviceAudioProcessing however, I'm not sure I understand it's purpose.
Following the best examples I've found, I proceed to create a graph, and use that to get an InputNode as such:
var creationResult = await AudioGraph.CreateAsync(settings);
if (creationResult.Status != AudioGraphCreationStatus.Success)
return;
_graph = creationResult.Graph;
var inputNodeCreationResult = await _graph.CreateDeviceInputNodeAsync(Windows.Media.Capture.MediaCategory.Media);
if (inputNodeCreationResult.Status != AudioDeviceNodeCreationStatus.Success)
{
DestroyGraph();
return;
}
_inputNode = inputNodeCreationResult.DeviceInputNode;
From here on, I'm running blind. Not finding any good tutorials, examples or documentation to help me.
I am only interested in sound level (dB), not the waveform. Is there anyone that can help me complete this, or point me to some decent documentation?

"Scenario 2: Device Capture" from the Windows Universal Samples - Audio Creation project should provide some guidance. From your code it looks like you're on track. Might just be a case of adding the following:
_frameOutputNode = _graph.CreateFrameOutputNode();
_frameOutputNode.Start();
_graph.QuantumProcessed += Graph_QuantumProcessed;
_graph.Start();
And using the Graph_QuantumProcessed callback to analyse the AudioFrame provided by a call to _frameOutputNode.GetFrame().
Hope it helps.

Related

Change sample rate of audiocard with WasapiOut Naudio

I want to chose a specific sample rate for my audio card programmatically in c# with Naudio.
My output is a WasapiOut in exclusive mode.
I already tried a lot of things, but nothing worked and I've searched everywhere and I only found this : How to Change Speaker Configuration in Windows in C#?
But they didn't really find a right solution.
Here's my WasapiOut :
var enumerator = new MMDeviceEnumerator();
MMDevice device = enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active).FirstOrDefault(d => d.DeviceFriendlyName == name);
outputDevice = new WasapiOut(device, AudioClientShareMode.Exclusive, false,200);
What I don't understand is that here :
https://github.com/naudio/NAudio/blob/master/Docs/WasapiOut.md
It says that :
"If you choose AudioClientShareMode.Exclusive then you are requesting exclusive access to the sound card. The benefits of this approach are that you can specify the exact sample rate you want"
And I didn't find anywhere how to specify the sample rate.
If someone here know the answer it would be great, thanks !
Edit :
I think I found a way by doing this :
var waveFormat5 = WaveFormat.CreateIeeeFloatWaveFormat(Int32.Parse(comboBox1.Text), 2);
var test2 = new MixingSampleProvider(waveFormat5);
var audioFile = new AudioFileReader("test.wav");
var input = audioFile;
test2.ReadFully = true;
test2.AddMixerInput(new AutoDisposeFileReader(input,waveFormat5));
outputDevice.Init(test2);
With "outputDevice" as my WasapiOut.
So I set the ouputDevice sample rate to the one that I chose with the Mixing Sample Provider and then I send an audiofile to that Mixer, is that the right way to do it ?
Because my audiofile sample rate is at 44100, and I chose to put my outputDevice sample rate to also 44100, but when I make outputDevice.Play(), the sound that I ear is faster than the original.
Once you've created an instance of WasapiOut you call Init passing the audio you want to play. It will try to use the sample rate (and WaveFormat) of that audio directly, assuming the soundcard supports it. Usi
I solved my problem, I used an AudioPlaybackEngine (https://markheath.net/post/fire-and-forget-audio-playback-with) with a MixingSampleProvider, and a try/catch to handle the message error of "the inputs are not a the same sample rate".

Play audio from a stream in UWP

I'm basically asking the same thing that was asked here, however, that question was asked 8 years ago and the answer is no longer applicable to UWP.
I have a audio stream with http://someurl.com/stream that streams in audio/ogg format. I would like to be able to play that from an UWP app.
I see the NAudio library recommended a lot (after all, it's used in the above example), however it's very larger and has fairly lackluster documentation and very few up-to-date examples (they used to have a streaming example, but from what I'm able to download off Codeplex, it was replaced with a regular local-file player example). I'm not experience enough to make sense of the little documentation and example code they do have.
I'm honestly not even sure where to begin. I've never handled a stream like this (or any stream). Maybe the NAudio library isn't the way to go?
Code would be appreciated, but even pointers to sources where I could read up on playing such stream would be very helpful as my google-fu has failed me.
Thank you.
EDIT:
private void PlayMedia() {
System.Uri manifestUri = new Uri("http://amssamples.streaming.mediaservices.windows.net/49b57c87-f5f3-48b3-ba22-c55cfdffa9cb/Sintel.ism/manifest(format=m3u8-aapl)");
var mediaPlayer = new Windows.Media.Playback.MediaPlayer();
~~~~~~~~~~~~ -> "'Media Player' does not contain a constructor that takes 0 arguments."
mediaPlayer.Source = MediaSource.CreateFromUri(manifestUri);
mediaPlayer.Play();
}
but I can't get the MediaPlayer class to work. It says for example the x.Play() doesn't exist.
You have not posted your code segment. So I could not locate the problem of Visual Studio alerting "doesn't exist" accurately. If you want to use "MediaPlayer" class please add Windows.Media.Core and Windows.Media.Playback namespace at first. And you could reference the following code implementing a basic mediaplayer.
using Windows.Media.Core;
using Windows.Media.Playback;
......
private void PlayMedia()
{
System.Uri manifestUri = new Uri("http://amssamples.streaming.mediaservices.windows.net/49b57c87-f5f3-48b3-ba22-c55cfdffa9cb/Sintel.ism/manifest(format=m3u8-aapl)");
var mediaPlayer = new MediaPlayer();
mediaPlayer.Source = MediaSource.CreateFromUri(manifestUri);
mediaPlayer.Play();
}
The error message of Media Player does not contain a constructor that takes 0 arguments is means that there is no constructor with no arguments in the MediaPlayer class. Please try use the full name of constructor with namespace.
var mediaPlayer = new Windows.Media.Playback.MediaPlayer();

TFS working with IBuildController in C#

I want to trigger a build from C#
In the build I need to change the default BuildController. My code look like this:
IBuildRequest buildRequest = BuildDefinition.CreateBuildRequest();
if(changebuildcontroller)
{
buildRequest.DropLocation = #"\\zzz.Domain.com\yyy$\TFS\Drop";
buildRequest.BuildController = **???**;
}
...
var queuedBuild = buildServer.QueueBuild(buildRequest);
Questions:
I would like to know how to find a list of buildcontrollers.
Any advice about how to understand the TFS object model will be appreciated. I looked at MSDN articles like this, but I do not see how it should help me. I used Google to find implementations of other objects in the Microsoft.TeamFoundation.Build.Client namespace.
It helped looking at another assignment for a while :)
If anyone else run into the same problem Use the Ibuildserver object to get a list of IBuildController
buildServer = (IBuildServer)teamProjectCollection.GetService(typeof(IBuildServer));
IBuildController[] buildserverlist = buildServer.QueryBuildControllers();

C# code completion with NRefactory 5

I just found out about NRefactory 5 and I would guess, that it is the most suitable solution for my current problem. At the moment I'm developing a little C# scripting application for which I would like to provide code completion. Until recently I've done this using the "Roslyn" project from Microsoft. But as the latest update of this project requires .Net Framework 4.5 I can't use this any more as I would like the app to run under Win XP as well. So I have to switch to another technology here.
My problem is not the compilation stuff. This can be done, with some more effort, by .Net CodeDomProvider as well. The problem ist the code completion stuff. As far as I know, NRefactory 5 provides everything that is required to provide code completion (parser, type system etc.) but I just can't figure out how to use it. I took a look at SharpDevelop source code but they don't use NRefactory 5 for code completion there, they only use it as decompiler. As I couldn't find an example on how to use it for code completion in the net as well I thought that I might find some help here.
The situation is as follows. I have one single file containing the script code. Actually it is not even a file but a string which I get from the editor control (by the way: I'm using AvalonEdit for this. Great editor!) and some assemblies that needs to get referenced. So, no solution files, no project files etc. just one string of source code and the assemblies.
I've taken a look at the Demo that comes with NRefactory 5 and the article on code project and got up with something like this:
var unresolvedTypeSystem = syntaxTree.ToTypeSystem();
IProjectContent pc = new CSharpProjectContent();
// Add parsed files to the type system
pc = pc.AddOrUpdateFiles(unresolvedTypeSystem);
// Add referenced assemblies:
pc = pc.AddAssemblyReferences(new CecilLoader().LoadAssemblyFile(
System.Reflection.Assembly.GetAssembly(typeof(Object)).Location));
My problem is that I have no clue on how to go on. I'm not even sure if it is the right approach to accomplish my goal. How to use the CSharpCompletionEngine? What else is required? etc. You see there are many things that are very unclear at the moment and I hope you can bring some light into this.
Thank you all very much in advance!
I've just compiled and example project that does C# code completion with AvalonEdit and NRefactory.
It can be found on Github here.
Take a look at method ICSharpCode.NRefactory.CSharp.CodeCompletion.CreateEngine. You need to create an instance of CSharpCompletionEngine and pass in the correct document and the resolvers. I managed to get it working for CTRL+Space compltition scenario. However I am having troubles with references to types that are in other namespaces. It looks like CSharpTypeResolveContext does not take into account the using namespace statements - If I resolve the references with CSharpAstResolver, they are resolved OK, but I am unable to correctly use this resolver in code completition scenario...
UPDATE #1:
I've just managed to get the working by obtaining resolver from unresolved fail.
Here is the snippet:
var mb = new DefaultCompletionContextProvider(doc, unresolvedFile);
var resolver3 = unresolvedFile.GetResolver(cmp, loc); // get the resolver from unresolvedFile
var engine = new CSharpCompletionEngine(doc, mb, new CodeCompletionBugTests.TestFactory(resolver3), pctx, resolver3.CurrentTypeResolveContext );
Update #2:
Here is the complete method. It references classes from unit test projects, sou you would need to reference/copy them into your project:
public static IEnumerable<ICompletionData> DoCodeComplete(string editorText, int offset) // not the best way to put in the whole string every time
{
var doc = new ReadOnlyDocument(editorText);
var location = doc.GetLocation(offset);
string parsedText = editorText; // TODO: Why there are different values in test cases?
var syntaxTree = new CSharpParser().Parse(parsedText, "program.cs");
syntaxTree.Freeze();
var unresolvedFile = syntaxTree.ToTypeSystem();
var mb = new DefaultCompletionContextProvider(doc, unresolvedFile);
IProjectContent pctx = new CSharpProjectContent();
var refs = new List<IUnresolvedAssembly> { mscorlib.Value, systemCore.Value, systemAssembly.Value};
pctx = pctx.AddAssemblyReferences(refs);
pctx = pctx.AddOrUpdateFiles(unresolvedFile);
var cmp = pctx.CreateCompilation();
var resolver3 = unresolvedFile.GetResolver(cmp, location);
var engine = new CSharpCompletionEngine(doc, mb, new CodeCompletionBugTests.TestFactory(resolver3), pctx, resolver3.CurrentTypeResolveContext );
engine.EolMarker = Environment.NewLine;
engine.FormattingPolicy = FormattingOptionsFactory.CreateMono();
var data = engine.GetCompletionData(offset, controlSpace: false);
return data;
}
}
Hope it helps,
Matra
NRefactory 5 is being used in SharpDevelop 5. The source code for SharpDevelop 5 is currently available in the newNR branch on github. I would take a look at the CSharpCompletionBinding class which has code to display a completion list window using information from NRefactory's CSharpCompletionEngine.

verbot 5 sdk - loading KnowledgeBases

I'm looking for help from anyone who's worked with the verbot sdk.
I'm making a program that I want to use the LearnedKnowledge.vkb, Teacher.vkb, and any standard bot (julia, for example). Those who've used this before will know that with the rules in Teacher, you can essentially write responses to things that the bot doesn't understand, and train it on the fly.
I'm planning on using speech recognition and text-to-speech, but my problem right now is that after I load the knowledgebases, I can't seem to get any response from the bot.
Here's what I have: The Verbot5Library.dll, from verbots.sourceforge.net (I got the editor and player too, to make sure the files were working). In my program, I set up the variables as such:
Verbot5Engine verbot = new Verbot5Engine();
KnowledgeBase kb = new KnowledgeBase();
KnowledgeBaseItem kbi = new KnowledgeBaseItem();
State state = new State();
XMLToolbox xmlToolboxKB = new XMLToolbox(typeof(KnowledgeBase));
Then I initialize the verbot engine and load the kbs:
// using the xmlToolboxKB method I saw in this forum: http://www.verbots.com/forums/viewtopic.php?t=2984
kbi.Fullpath = #"C:\\[full path to kb...]\\";
kbi.Filename = "LearnedKnowledge.vkb";
kb = (KnowledgeBase)xmlToolboxKB.LoadXML(kbi.Fullpath + kbi.Filename);
verbot.AddKnowledgeBase(kb, kbi);
kbi.Filename = "julia.vkb";
kb = (KnowledgeBase)xmlToolboxKB.LoadXML(kbi.Fullpath + kbi.Filename);
verbot.AddKnowledgeBase(kb, kbi);
//trying to use LoadKnowledgeBase and LoadCompiledKnowledgeBase methods: verbot.LoadKnowledgeBase("C:\\[full path to kb...]\\LearnedKnowledge.vkb");
//verbot.LoadCompiledKnowledgeBase("C:\\[full path...]\\julia.ckb");
//verbot.LoadCompiledKnowledgeBase("C:\\[full path...]\\Teacher.ckb");
// set up state
state.CurrentKBs.Add("C:\\[full path...]\\LearnedKnowledge.vkb");
state.CurrentKBs.Add("C:\\[full path...]\\Teacher.vkb");
state.CurrentKBs.Add("C:\\[full path...]\\julia.ckb");
Finally, I attempt to get a response from the verbot engine:
Reply reply = verbot.GetReply("hello", state);
if (reply != null)
Console.WriteLine(reply.AgentText);
else
Console.WriteLine("No reply found.");
I know julia has a response for "hello", as I've tested it with the editor. But all it ever returns is "No reply found". This code has been taken from the example console program in the SDK download (as very little documentation is available). That's why I need some pointers from someone who's familiar with the SDK.
Am I not loading the KBs correctly? Do they all need to be compiled (.ckb) instead of the XML files (.vkb)? I've used the verbot.OnKnowledgeBaseLoadError event handler and I get no errors. I even removed the resource file Default.vsn needed to load the Teacher, and it throws an error when trying to load it so I'm pretty sure it's all loading correctly. So why do I always get "No reply found"?
resolved: see http://www.verbots.com/forums/viewtopic.php?p=13021#13021

Categories

Resources