I would like to load an audio wav file in My Xamarin forms project.
The audio file is in SpeechApp=>Data=>audio.wav
I am using the Azure AudioConfig function like this:
var taskCompleteionSource = new TaskCompletionSource<int>();
var config = SpeechConfig.FromSubscription("xxx", "xx");
var transcriptionStringBuilder = new StringBuilder();
// Replace the language with your language in BCP-47 format, e.g., en-US.
var language = "fr-FR";
config.SpeechRecognitionLanguage = language;
config.OutputFormat = OutputFormat.Detailed;
using (var audioInput = AudioConfig.FromWavFileInput("SpeechApp.Data.audio.wav"))
{
using (var recognizer = new SpeechRecognizer(config, audioInput))
{
// Stops recognition.
await recognizer.StopContinuousRecognitionAsync();
}
}
But It is not working and I have this error : System.DllNotFoundException: Microsoft.CognitiveServices.Speech.core.dll
My error comes from this lines : var config = SpeechConfig.FromSubscription()
I was inspired from this web site :click here
Thanks for your help
Could you please try something like below:
using (var audioInput = AudioConfig.FromWavFileInput(#"SpeechApp.Data.audio.wav"))
{
using (var recognizer = new SpeechRecognizer(config, audioInput))
{
}
You can refer this link for more samples in different languages.
Hope it helps.
Related
I was trying to create simple service that listens for keyword from speech. I was using Microsoft.CognitiveServices.Speech ver 1.24.1 and proceeding with official documentation but got error while trying to read KeywordRecognitionodel from file, file is accessible from that path. Also tried relative and absolute path.
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Audio;
namespace HandyCook.Services
{
internal class KeyWordRecognizerService
{
public KeyWordRecognizerService()
{
StartRecognizing();
}
private async void StartRecognizing()
{
var audioConfig = AudioConfig.FromDefaultMicrophoneInput();
var recognizer = new KeywordRecognizer(audioConfig);
recognizer.Recognized += (s, e) =>
{
Console.WriteLine($"{e.Result.Text} DETECTED");
};
var stream = await FileSystem.Current.OpenAppPackageFileAsync("XXX.table"); //accessible
//Exception with an error code: 0x8 (SPXERR_FILE_OPEN_FAILED)
var keywordModel = KeywordRecognitionModel.FromFile(Path.Combine(FileSystem.Current.AppDataDirectory, "XXX.table"));
var result = recognizer.RecognizeOnceAsync(keywordModel);
result.Wait();
}
}
}
To reproduce the error just simply create new MAUI Blazor App, add nuget package 'Microsoft.CognitiveServices.Speech 1.24.1', add service as singleton in MauiProgram then inject in Index.razor. I'm pasting also table file and solution explorer view.
table file: https://sendanywhe.re/18U3PXF8
I have created a chat bot using microsoft bot framework v4 sdk. I wanted to log bot user and bot messages to cosmos db.
i am able to log only user messages using below blog https://learn.microsoft.com/en-us/azure/bot-service/bot-builder-howto-v4-storage?view=azure-bot-service-4.0&tabs=csharp#using-cosmos-db .
I expect to log both user and bot responses.
Thankfully, this is pretty easy since ItranscriptLogger and TranscriptLoggerMiddleware already exist.
Create your TranscriptStore Class (new Class file)
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Azure;
using Microsoft.Bot.Schema;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace QuickTestBot_CSharp
{
public class CosmosTranscriptStore : ITranscriptLogger
{
private CosmosDbStorage _storage;
public CosmosTranscriptStore(CosmosDbStorageOptions config)
{
_storage = new CosmosDbStorage(config);
}
public async Task LogActivityAsync(IActivity activity)
{
// activity only contains Text if this is a message
var isMessage = activity.AsMessageActivity() != null ? true : false;
if (isMessage)
{
// Customize this to save whatever data you want
var data = new
{
From = activity.From,
To = activity.Recipient,
Text = activity.AsMessageActivity().Text,
};
var document = new Dictionary<string, object>();
// activity.Id is being used as the Cosmos Document Id
document.Add(activity.Id, data);
await _storage.WriteAsync(document, new CancellationToken());
}
}
}
}
Create and Add the Middleware (in Startup.cs)
[...]
var config = new CosmosDbStorageOptions
{
AuthKey = "<YourAuthKey>",
CollectionId = "<whateverYouWant>",
CosmosDBEndpoint = new Uri("https://<YourEndpoint>.documents.azure.com:443"),
DatabaseId = "<whateverYouWant>",
};
var transcriptMiddleware = new TranscriptLoggerMiddleware(new CosmosTranscriptStore(config));
var middleware = options.Middleware;
middleware.Add(transcriptMiddleware);
[...]
Result:
Note:
This is probably the easiest/best way to do it. However, you can also capture outgoing activities under OnTurnAsync() using turnContext.OnSendActivities() and then write the outgoing activity to storage, as well.
I'd like to use Roslyn to analyze semantic information within the context of a block of C# code inside a Razor View.
Is there any way (within Visual Studio 2015, or even in a unit test) to get the SemanticModel that represents this code?
Razor files contain a C# projection buffer with the generated C# code (including the parts that you don't write yourself). This buffer has full Roslyn services and is exactly what you're looking for.
You need to walk through the TextView's BufferGraph and find the CSharp buffer; you can then get its Document and semantic model.
If you're starting from the cursor location, you need simply need to map that location to a CSharp buffer.
Note that it is perfectly legal for a TextView to contain multiple CSharp buffers. (although the Razor editor will never do that)
If you aren't working in a TextView, you need to do all of this yourself; you need to run the Razor source through the Razor compiler to get the generated C# source, then compile that with Roslyn to get a semantic model.
Extract the code representing the view from the Razor view file using RazorTemplateEngine.GenerateCode and CSharpCodeProvider.GenerateCodeFromCompileUnit (or the VBCodeProvider if you want the intermediate source as VB.NET). You can then use Roslyn to parse the code.
There's an example of using Roslyn with Razor view files here.
Take note that GenerateCode carries a caveat:
This type/member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
Just in case anyone else gets stuck on this, I have mini sample app which may help.
I had a CMS class like this:
public partial class CMS
{
public static string SomeKey
{
get { return (string) ResourceProvider.GetResource("some_key"); }
}
// ... and many more ...
}
... and I wanted to find out which of these were used throughout my solution for a report ... Enter Roslyn!
The following app will print out the count for the used and unused references:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Razor;
namespace TranslationSniffer
{
class Program
{
static void Main(string[] args)
{
new Program().Go().Wait();
}
public async Task Go()
{
// Roslyn!
var ws = MSBuildWorkspace.Create();
// Store the translation keys...
List<string> used = new List<string>();
List<string> delete = new List<string>();
string solutionRoot = #"C:\_Code\PathToProject\";
string sln = solutionRoot + "MySolution.sln";
// Load the solution, and find all the cshtml Razor views...
var solution = await ws.OpenSolutionAsync(sln);
var mainProj = solution.Projects.Where(x => x.Name == "ConsumerWeb").Single();
FileInfo[] cshtmls = new DirectoryInfo(solutionRoot).GetFiles("*.cshtml", SearchOption.AllDirectories);
// Go through each Razor View - generate the equivalent CS and add to the project for compilation.
var host = new RazorEngineHost(RazorCodeLanguage.Languages["cshtml"]);
var razor = new RazorTemplateEngine(host);
var cs = new CSharpCodeProvider();
var csOptions = new CodeGeneratorOptions();
foreach (var cshtml in cshtmls)
{
using (StreamReader re = new StreamReader(cshtml.FullName))
{
try
{
// Let Razor do it's thang...
var compileUnit = razor.GenerateCode(re).GeneratedCode;
// Pull the code into a stringbuilder, and append to the main project:
StringBuilder sb = new StringBuilder();
using (StringWriter rw = new StringWriter(sb))
{
cs.GenerateCodeFromCompileUnit(compileUnit, rw, csOptions);
}
// Get the new immutable project
var doc = mainProj.AddDocument(cshtml.Name + ".cs", sb.ToString());
mainProj = doc.Project;
}
catch(Exception ex)
{
Console.WriteLine("Compile fail for: {0}", cshtml.Name);
// throw;
}
continue;
}
}
// We now have a new immutable solution, as we have changed the project instance...
solution = mainProj.Solution;
// Pull out our application translation list (its in a static class called 'CMS'):
var mainCompile = await mainProj.GetCompilationAsync();
var mainModel = mainCompile.GetTypeByMetadataName("Resources.CMS");
var translations = mainModel.GetMembers().Where(x => x.Kind == SymbolKind.Property).ToList();
foreach (var translation in translations)
{
var references = await SymbolFinder.FindReferencesAsync(translation, solution) ;
if (!references.First().Locations.Any())
{
Console.WriteLine("{0} translation is not used!", translation.Name);
delete.Add(translation.Name);
}
else
{
Console.WriteLine("{0} :in: {1}", translation.Name, references.First().Locations.First().Document.Name);
used.Add(translation.Name);
}
}
Console.WriteLine();
Console.WriteLine("Used references {0}. Unused references: {1}", used.Count, delete.Count);
return;
}
}
}
Roslyn only models cshtml files while they are open, but during that time they are similar to every other source file in the Workspace model.
Is there something specific you have tried that isn't working?
to show a news feed, music, sports. thanks.
private void loadfeedYoutube()
{
string feedUrl="https://gdata.youtube.com/feeds/api/standardfeeds/most_popular";
var request=new
Feed<Video> videoFeed = request.Get<Video>(new Uri(feedUrl));
printVideoFeed(videoFeed);
static void printVideoFeed(Feed<Video> feed)
{
foreach (Video entry in feed.Entries)
{
printVideoEntry(entry);
}
}
}
I'm using:
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
Error: not finding Feed, request...
There is using myToolkit
private void GetYoutubeChannel(string feedXML)
{
try
{
SyndicationFeed feed = new SyndicationFeed();
feed.Load(feedXML);
List<YoutubeVideo> videosList = new List<YoutubeVideo>();
YoutubeVideo video;
foreach (SyndicationItem item in feed.Items)
{
video = new YoutubeVideo();
video.YoutubeLink = item.Links[0].Uri;
string a = video.YoutubeLink.ToString().Remove(0, 31);
video.Id = a.Substring(0, 11);
video.Title = item.Title.Text;
video.PubDate = item.PublishedDate.DateTime;
video.Thumbnail = YouTube.GetThumbnailUri(video.Id, YouTubeThumbnailSize.Large);
videosList.Add(video);
}
MainListBox.ItemsSource = videosList;
}
catch { }
}
Lê Thiên Hoàng
You can try to use SyndicationFeed to help you,
check this example, which using Mytoolkit project to implement.
http://code.msdn.microsoft.com/windowsapps/Youtube-Sample-Get-Youtube-e9a3e0be
and you using feedUrl method is an old api which is v2 not v3.
#Lê Thiên Hoàng
using http://gdata.youtube.com/demo/index.html to generate you want to get.
if you want get music popular, then your RESTFul Api link is:
http://gdata.youtube.com/feeds/api/standardfeeds/most_viewed/-/{http://gdata.youtube.com/schemas/2007/categories.cat}Music?alt=rss
But I recommend if you can, using Youtube API Version3, is better and easier to get different category video.
How can I get the phonics sound by pushing any letter key? For example, I want to get the phonics sound of A by pushing the 'A' key.
I'm using Microsoft SAPI v5.1. Can you point me in the right direction please?
Add reference to System.Speech assembly.
Add using System.Speech.Synthesis;
using (var speechSynthesizer = new SpeechSynthesizer())
{
speechSynthesizer.Speak("A");
speechSynthesizer.Speak("B");
speechSynthesizer.Speak("C");
}
For example like this:
using (var speechSynthesizer = new SpeechSynthesizer())
{
while (true)
{
var consoleKey = Console.ReadKey();
if (consoleKey.Key == ConsoleKey.Escape)
break;
var text = consoleKey.KeyChar.ToString();
speechSynthesizer.Speak(text);
}
}