Playing Music from resources C# - c#

I want to play some background music inside the launcher for my new project. But I get an error.
private void playlooping()
{
SoundPlayer.PlayLooping(system.Resources.Bgm);
}
//Bgm is the name of the song.
For some reason I get the error
no overload for method 'PlayLooping' Takes 1 arguments

As I mentioned in the comment, PlayLooping does not take any arguments. So you need to specify the sound you want to play somewhere else. This is done either by setting it via the SoundPlayer-Constructor like this:
// via string path
var soundPlayer = new SoundPlayer(#"C:\somePath\someFile.wav");
// via stream
var soundPlayer = new SoundPlayer(musicStream);
So if your resource is a string you should be good to go with:
var soundPlayer = new SoundPlayer(system.Resources.Bgm);
Alternative is to set the string-path or stream after instantiating your SoundPlayer via the Site- or Stream-Properties of your SoundPlayer object:
var soundPlayer = new SoundPlayer();
// via path
soundPlayer.Site = #"C:\path\test.wav";
// via stream
soundPlayer.Stream = someStream;
After setting this up correclty you should be good calling PlayLooping. So your final code should be looking like this (works for me in a test windows forms application, with the soundfile simply put in my debug folder):
var soundPlayer = new SoundPlayer("test.wav");
soundPlayer.PlayLooping();
You can find the full documentation on the SoundPlayer here: https://msdn.microsoft.com/en-us/library/system.media.soundplayer(v=vs.110).aspx

Related

How to use Google Cloud Speech (V1 API) for speech to text - need to be able to process over 3 hours audio files properly and efficiently

I am looking for documentation and stuff but could not find a solution yet
Installed NuGet package
Also generated API key
However can't find proper documentation how to use API key
Moreover, I want to be able to upload very long audio files
So what would be the proper way to upload up to 3 hours audio files and get their results?
I have 300$ budget so should be enough
Here my so far code
This code currently fails since I have not set the credentials correctly at the moment which I don't know how to
I also have service account file ready to use
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var speech = SpeechClient.Create();
var config = new RecognitionConfig
{
Encoding = RecognitionConfig.Types.AudioEncoding.Flac,
SampleRateHertz = 48000,
LanguageCode = LanguageCodes.English.UnitedStates
};
var audio = RecognitionAudio.FromStorageUri("1m.flac");
var response = speech.Recognize(config, audio);
foreach (var result in response.Results)
{
foreach (var alternative in result.Alternatives)
{
Debug.WriteLine(alternative.Transcript);
}
}
}
}
I don't want to set environment variable. I have both API key and Service Account json file. How can I manually set?
You need to use the SpeechClientBuilder to create a SpeechClient with custom credentials, if you don't want to use the environment variable. Assuming you've got a service account file somewhere, change this:
var speech = SpeechClient.Create();
to this:
var speech = new SpeechClientBuilder
{
CredentialsPath = "/path/to/your/file"
}.Build();
Note that to perform a long-running recognition operation, you should also use the LongRunningRecognize method - I strongly suspect your current RPC will fail, either explicitly because it's trying to run on a file that's too large, or it'll just time out.
You need to set the environment variable before create the instance of Speech:
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "text-tospeech.json");
Where the second param (text-tospeech.json) is your file with credentials generated by Google Api.

Muting a Mic Using AudioDeviceController

Hello Eveyone I am trying to mute/unmute a default mic using AudioDeviceController but it looks like I cannot initialize the variable.
I have since used AudioDeviceModulesManager because you can get an object by device ID.
How do I initilize the Variabale like I do with AudioDeviceModulesManager .
public App()
{
var endpointID = MediaDevice.GetDefaultAudioCaptureId(AudioDeviceRole.Default);
AudioDeviceModulesManager MyController = new AudioDeviceModulesManager(endpointID);
var thing = MyController.FindAll();
var test = thing[0];
}
Thanks for your interesting, derive from official document remake part, To get an instance of this object, retrieve the MediaCapture.AudioDeviceController property.
So we can only get AudioDeviceController instance from MediaCapture class. For more detail please check this Basic photo, video, and audio capture with MediaCapture tutorial.

Play audio url using xamarin MediaPlayer

Why xamarin MediaPlayer (on Xamarin.Android) can play audio as a stream from a link like this (mediaUrl1) :
https://ia800806.us.archive.org/15/items/Mp3Playlist_555/AaronNeville-CrazyLove.mp3
But can't do it from a link like this (mediaUrl2):
http://api-streaming.youscribe.com/v1/products/2919465/documents/3214936/audio/stream
private MediaPlayer player;
//..
player = new MediaPlayer();
player.SetAudioStreamType(Stream.Music);
//..
await player.SetDataSourceAsync(ApplicationContext, Android.Net.Uri.Parse(mediaUrl));
//..
player.PrepareAsync();
//..
Is there a way to play the link above (mediaUrl2) without (of course) downloading the file first?
Here is the full source of the sample i am using. Any help would be appreciated.
http://api-streaming.youscribe.com/v1/products/2919465/documents/3214936/audio/stream
That is an HTTP mpga stream and is not directly supported by any of the Android APIs that I know of and thus is not supported by MediaPlayer (consult the Android Support Media Formats for further reading).
You can review the logcat output of your MediaPlayer code and you will see output like:
[MediaPlayerNative] start called in state 4, mPlayer(0x8efb7240)
[MediaPlayerNative] error (-38, 0)
[MediaPlayer] Error (-38,0)
[MediaHTTPConnection] readAt 1161613 / 32768 => java.net.ProtocolException
[MediaHTTPConnection] readAt 1161613 / 32768 => java.net.ProtocolException
[MediaPlayerNative] error (1, -2147483648)
[MediaPlayer] Error (1,-2147483648)
Google's Android ExoPlayer can stream that media format properly.
This is a really simple and very crude example of ExoPlayer, but it will show you that it does play that stream:
ExoPlayer Example:
var mediaUrl = "http://api-streaming.youscribe.com/v1/products/2919465/documents/3214936/audio/stream";
var mediaUri = Android.Net.Uri.Parse(mediaUrl);
var userAgent = Util.GetUserAgent(this, "ExoPlayerDemo");
var defaultHttpDataSourceFactory = new DefaultHttpDataSourceFactory(userAgent);
var defaultDataSourceFactory = new DefaultDataSourceFactory(this, null, defaultHttpDataSourceFactory);
var extractorMediaSource = new ExtractorMediaSource(mediaUri, defaultDataSourceFactory, new DefaultExtractorsFactory(), null, null);
var defaultBandwidthMeter = new DefaultBandwidthMeter();
var adaptiveTrackSelectionFactory = new AdaptiveTrackSelection.Factory(defaultBandwidthMeter);
var defaultTrackSelector = new DefaultTrackSelector(adaptiveTrackSelectionFactory);
exoPlayer = ExoPlayerFactory.NewSimpleInstance(this, defaultTrackSelector);
exoPlayer.Prepare(extractorMediaSource);
exoPlayer.PlayWhenReady = true;
Note: exoPlayer is a class-level variable of SimpleExoPlayer type
Note: this is using the Xamarin.Android binding libraries from the Xam.Plugins.Android.ExoPlayer package
ExoPlayer Docs:
https://developer.android.com/guide/topics/media/exoplayer

Speech recognition only listens for Commands in my dictionary?

Okay so i am working on my program. The problem is that whenever spymode = true, it doesnt register whatever i am saying to the text file. It just registers the set commands in "CommandsList" dictionary. So whenever i say like "twitch" which is a command in that dictionary it will write that to the spymodeLog.txt file. But whenever i say something that is not a command, for example "hello my name is Robin" , that will not be written to the .txt file. It only takes commands in my dictionary and outputs it to the file whenever i say them. Why is this? and how can i fix it? really odd.
static Dictionary<string, string> CommandsList = new Dictionary<string, string>();
internal static void recEngine_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
if (keyHold == true)
{
string command = "";
if (CommandsList.TryGetValue(e.Result.Text, out command))
{
System.Diagnostics.Process.Start(command);
}
}
if (spymode == true)
{
DateTime now = DateTime.Now;
string path = Application.StartupPath + "spymodeLog.txt";
if (File.Exists(path))
{
using (StreamWriter wr = File.AppendText(path))
{
wr.WriteLine(e.Result.Text.ToString());
}
}
else if(!File.Exists(path))
{
using (var wr = new StreamWriter("spymodeLog.txt", true))
{
wr.WriteLine(e.Result.Text.ToString());
}
}
}
}
SpeechRecognized event fire when a command from the dictionnary has been recognized, hence the name of the event.
What you want is the SpeechDetected event which from the help says it fire when it recognize something has been said.
Each speech recognizer has an algorithm to distinguish between silence and speech. When the SpeechRecognitionEngine performs a speech recognition operation, it raises the SpeechDetected event when its algorithm identifies the input as speech.
This event will allow you to get the actual position when an audio was captured. This allow you to go find that audio portion and save it to a file or send it in the methods that allow you to convert audio to text (i do not remember the methods but they are there, i have used it in the past)
Second method which doesn't work on everyone computer. 1 out of 3 of my PC actually works with this method and this method is to create an instance of a special grammar disctionnary called DictationGrammar
What you do is create a new instance of this class. You have 3 ways to do so, either normal, spelling or default of the computer accessbility option.
default computer accessibility :
var grammar = new DictationGrammar();
Normal :
var grammar = new DictationGrammar("grammar:dictation");
Spelling :
var grammar = new DictationGrammar("grammar:dictation#spelling");
than use that dictionnary with the combinaison of all those you want and you can create a tree of choices that lead to the generic recognition. Me in my old app i used to have the keyword "Note" that had to be said and then it was falling on the DictationGrammar and started to recognize all text.
Since it didn't work on all computers while other commands where perfectly working i assumed it has something to do with wrong language of dictation grammar being loaded or something like that but there was no option to change that so i went with SpeechDetected and converted the audio to text myself.

Convert Torrent Magnet link to a .torrent file with c#

Is there a way to do it? I already tried with monotorrent, but due to the lack of up-to-date documentation i coudn't get it to work. I've already tried this with monotorrent, but still i can't find a way to get the .torrent file or even start the download to get the .torrent ...
The following piece of code was made that question as base, but it doesn't save anything to "D:\A" or to "D:\TorrentSave"
private void GerarTorrent(string magnet)
{
MonoTorrent.Client.TorrentManager b = new MonoTorrent.Client.TorrentManager(new MonoTorrent.MagnetLink(magnet), "D:\\A", new MonoTorrent.Client.TorrentSettings(), "D:\\TorrentSave");
MonoTorrent.Client.EngineSettings engineSettings = new MonoTorrent.Client.EngineSettings();
MonoTorrent.Client.ClientEngine clientEngine = new MonoTorrent.Client.ClientEngine(engineSettings);
clientEngine.Register(b);
clientEngine.StartAll();
b.Start();
}
To generate the .torrent, it doesn't have to be monotorrent, in fact the only usage of this api would be for that, generating .torrent files from a magnet link...
EDIT: Updated code with my attempt on doing what Fᴀʀʜᴀɴ Aɴᴀᴍ said:
private void GerarTorrent(string hash)
{
MonoTorrent.Client.TorrentManager b = new MonoTorrent.Client.TorrentManager(MonoTorrent.InfoHash.FromHex(hash), "D:\\A", new MonoTorrent.Client.TorrentSettings(), "D:\\TorrentSave", new List<List<string>>());
MonoTorrent.Client.EngineSettings engineSettings = new MonoTorrent.Client.EngineSettings();
MonoTorrent.Client.ClientEngine clientEngine = new MonoTorrent.Client.ClientEngine(engineSettings);
clientEngine.Register(b);
clientEngine.StartAll();
b.Start();
}
Hash used = "5FC86BA08451CF4221E0091F31AF1A52C2219009"
You need to pass only the hash and not the entire magnet link to the TorrentManager constructor.
A magnet link looks like this:
magnet:?xt=urn:btih:18981bc9759950b4715ad46adcaf514e6a773cfe
So, a more generalized form:
magnet:?xt=urn:btih:<hash>
You need to extract this <hash> and pass it to the constructor:
manager = new TorrentManager(InfoHash.FromHex(hash), downloadsPath, torrentDefaults, downloadsPathForTorrent, new List<List<string>>());

Categories