public AudioPlayer(Resource resource, TabPage tab) { var soundData = (Sound)resource.Blocks[BlockType.DATA]; var stream = soundData.GetSoundStream(); waveOut = new WaveOutEvent(); if (soundData.Type == Sound.AudioFileType.WAV) { var rawSource = new WaveFileReader(stream); waveOut.Init(rawSource); } else if (soundData.Type == Sound.AudioFileType.MP3) { var rawSource = new Mp3FileReader(stream); waveOut.Init(rawSource); } else if (soundData.Type == Sound.AudioFileType.AAC) { var rawSource = new StreamMediaFoundationReader(stream); waveOut.Init(rawSource); } playButton = new Button(); playButton.Text = "Play"; playButton.TabIndex = 1; playButton.Size = new Size(100, 25); playButton.Click += PlayButton_Click; tab.Controls.Add(playButton); }
public static void Play(string url = "") { if (url != "") { bool initialized = false; do { try { InitUrl(url); WindowRenderer.newIndex(); current.bufferedStream = new bufferedStream(current); Stream piss = current.bufferedStream.getStream(); streamRead = new StreamMediaFoundationReader(piss, new MediaFoundationReader.MediaFoundationReaderSettings() { SingleReaderObject = true }); WaveOut.Init(streamRead); initialized = true; } catch (Exception e) { Console.WriteLine($"An error occured during initialization of player: {e.Message}"); } }while (!initialized); } WaveOut.Play(); }
public override Task PlayAsync() { log.Debug($"playing stream {musicSource}"); try { stream = GetSourceStream(); reader = new StreamMediaFoundationReader(stream); channel = new SampleChannel(reader, true); channel.Volume = 0.5f; player.PlaybackStopped += (o, e) => { stream.Dispose(); wc.Dispose(); RaisePlaybackStopped(); }; player.Init(reader); RaisePlaybackStarting(); player.Play(); } catch (System.Exception xe) { log.Error(xe); } return(Task.CompletedTask); }
private static void PlayEmbeddedResource(string type, string path) { try { Assembly a = Assembly.GetExecutingAssembly(); Stream s = a.GetManifestResourceStream($"GtaChaos.Models.{type}.{path}"); MediaFoundationReader reader = null; try { reader = new MediaFoundationReader($"{type}/{path}"); } catch (Exception) // Didn't find an override audio file, try to use the embedded one { reader = new StreamMediaFoundationReader(s); } WaveOutEvent outputDevice = new WaveOutEvent(); outputDevice.Init(reader); outputDevice.Play(); } catch (Exception) { // File not found >:( } }
private void Window_Loaded(object sender, RoutedEventArgs e) { mumbleLoopThread = new Thread(MumbleLoop); mumbleLoopThread.Start(); //Load and play _audioFile = new StreamMediaFoundationReader(new MemoryStream(Properties.Resources.uts_loop4)); _loop = new LoopStream(_audioFile); _outputDevice = new WaveOutEvent(); _outputDevice.Init(_loop); _outputDevice.Volume = 0; _outputDevice.Play(); }
public static void ConvertM4AToMp3(Stream m4AStream, string directory, ref Track song) //requires windows 8 or higher { using (var reader = new StreamMediaFoundationReader(m4AStream)) //this reader supports: MP3, AAC and WAV { var aaCtype = AudioSubtypes.MFAudioFormat_AAC; var bitrates = MediaFoundationEncoder.GetEncodeBitrates(aaCtype, reader.WaveFormat.SampleRate, reader.WaveFormat.Channels); song.LocalPath += ".mp3"; //conversion wil result in an mp3 MediaFoundationEncoder.EncodeToMp3(reader, song.LocalPath, bitrates[bitrates.GetUpperBound(0)]); } }
public async Task <ICanvasImage> RenderAsync(StorageFile selectedFile, IPeakProvider peakProvider, WaveFormRendererSettings settings) { var randomAcessStream = await selectedFile.OpenReadAsync(); using (var reader = new StreamMediaFoundationReader(randomAcessStream.AsStream())) { int bytesPerSample = (reader.WaveFormat.BitsPerSample / 8); var samples = reader.Length / (bytesPerSample); var samplesPerPixel = (int)(samples / settings.Width); var stepSize = settings.PixelsPerPeak + settings.SpacerPixels; peakProvider.Init(reader.ToSampleProvider(), samplesPerPixel * stepSize); return(Render(peakProvider, settings)); } }
public AudioPlayer(Resource resource, TabPage tab) { var soundData = (Sound)resource.Blocks[BlockType.DATA]; var stream = soundData.GetSoundStream(); waveOut = new WaveOutEvent(); try { if (soundData.Type == Sound.AudioFileType.WAV) { var rawSource = new WaveFileReader(stream); waveOut.Init(rawSource); } else if (soundData.Type == Sound.AudioFileType.MP3) { var builder = new Mp3FileReader.FrameDecompressorBuilder(wf => new Mp3FrameDecompressor(wf)); var rawSource = new Mp3FileReader(stream, builder); waveOut.Init(rawSource); } else if (soundData.Type == Sound.AudioFileType.AAC) { var rawSource = new StreamMediaFoundationReader(stream); waveOut.Init(rawSource); } playButton = new Button(); playButton.Text = "Play"; playButton.TabIndex = 1; playButton.Size = new Size(100, 25); playButton.Click += PlayButton_Click; playButton.Disposed += PlayButton_Disposed; tab.Controls.Add(playButton); } catch (Exception e) { Console.Error.WriteLine(e); var msg = new Label { Text = $"NAudio Exception: {e.Message}", Dock = DockStyle.Fill, }; tab.Controls.Add(msg); } }
void test_play_ByteArray_file_Unknow(string url) { byte[] bytes = new byte[] { }; if (url.StartsWith("http")) { using (Stream ms = new MemoryStream()) { using (Stream stream = WebRequest.Create(url) .GetResponse().GetResponseStream()) { List <byte> ls = new List <byte>(); byte[] buffer = new byte[32768]; int read; while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); ls.AddRange(buffer.Take(read)); } bytes = ls.ToArray(); } } } else { bytes = File.ReadAllBytes(url); } //var waveFormat = MediaFoundationReader.GetCurrentWaveFormat(bytes); using (var ms = new MemoryStream(bytes)) using (var mf = new StreamMediaFoundationReader(ms)) using (var wo = new WaveOutEvent()) { wo.Init(mf); wo.Play(); while (wo.PlaybackState == PlaybackState.Playing) { Thread.Sleep(1000); } } }
[NotNull] private static MemoryStream NormalizeAudioData(byte[] data) { #if NCRUNCH return(new MemoryStream(data)); #endif //Construct reader which can read the audio (whatever format it is in) var reader = new StreamMediaFoundationReader(new MemoryStream(data)); var sampleProvider = reader.ToSampleProvider(); // find the max peak float max = 0; var buffer = new float[reader.WaveFormat.SampleRate]; int read; do { read = sampleProvider.Read(buffer, 0, buffer.Length); if (read > 0) { max = Math.Max(max, Enumerable.Range(0, read).Select(i => Math.Abs(buffer[i])).Max()); } } while (read > 0); if (Math.Abs(max) < float.Epsilon || max > 1.0f) { throw new InvalidOperationException("Audio normalization failed to find a reasonable peak volume"); } //Write (as wav) with soft clipping and peak volume normalization var output = new MemoryStream((int)(reader.Length * 4)); var input = new SoftClipSampleProvider(new VolumeSampleProvider(sampleProvider) { Volume = 1 / max - 0.05f }); reader.Position = 0; WaveFileWriter.WriteWavFileToStream(output, input.ToWaveProvider16()); return(output); }
public AudioPlayer(Resource resource, TabPage tab) { var soundData = (Sound)resource.DataBlock; var stream = soundData.GetSoundStream(); try { WaveStream waveStream; switch (soundData.SoundType) { case Sound.AudioFileType.WAV: waveStream = new WaveFileReader(stream); break; case Sound.AudioFileType.MP3: waveStream = new Mp3FileReaderBase(stream, wf => new Mp3FrameDecompressor(wf)); break; case Sound.AudioFileType.AAC: waveStream = new StreamMediaFoundationReader(stream); break; default: throw new Exception($"Dont know how to play {soundData.SoundType}"); } var audio = new AudioPlaybackPanel(waveStream); tab.Controls.Add(audio); } catch (Exception e) { Console.Error.WriteLine(e); var msg = new Label { Text = $"NAudio Exception: {e.Message}", Dock = DockStyle.Fill, }; tab.Controls.Add(msg); } }
private void CleanUpAudio() { if (waveOut != null) { waveOut.Stop(); waveOut.Dispose(); waveOut = null; } if (decompressor != null) { decompressor.Dispose(); decompressor = null; } if (mediaReader != null) { mediaReader.Dispose(); mediaReader = null; } bufferedWaveProvider = null; stream.Flush(); }
private void MumbleLoop() { do { bool shouldRun = true; client.Mumble.Update(); if (!client.Mumble.IsAvailable) { shouldRun = false; } int mapId = client.Mumble.MapId; if (mapId == 0) { shouldRun = false; } if (shouldRun) { try { this.Dispatcher.Invoke(new Action <IGw2MumbleClient>(m => { //Adjust volume acording to elevation float volume = 0; float Yloc = Convert.ToSingle(m.AvatarPosition.Y); if (Yloc <= 0) { volume = map(Yloc, -30, 0, Convert.ToSingle(MaxVolume.Value), 0.01f); } else { volume = map(Yloc, 0, 3, 0.01f, 0f); } //Lets not get crazy here, keep it between 0 and 1 volume = Clamp(volume, 0, 1); _outputDevice.Volume = volume; volumeSlider.Value = volume; #if DEBUG DepthLabel.Content = $"Depth ({_outputDevice.Volume})"; #endif }), this.client.Mumble); } catch (ObjectDisposedException) { // The application is likely closing break; } } Thread.Sleep(1000 / 60); } while (!stopRequested); _outputDevice.Stop(); _outputDevice.Dispose(); _outputDevice = null; _audioFile.Dispose(); _audioFile = null; _loop.Dispose(); _loop = null; }
public void Initialize() { string url = "https://www.youtube.com/watch?v=SuperDuperFunURL"; Bufstr_yt bufstr = new Bufstr_yt(scrapePage(url), url); Process process = new Process(); ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; startInfo.FileName = "cmd.exe"; startInfo.Arguments = $"/C youtube-dl --get-url --print-traffic -f {bufstr.formatid} {url}"; process.StartInfo = startInfo; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.Start(); process.WaitForExit(); string hsc = "header: Set-Cookie:"; WebRequest req = HttpWebRequest.Create("http://www.retardedispsayswhat.net"); string youtubedlres = process.StandardOutput.ReadToEnd(); foreach (string line in youtubedlres.Split('\n')) { if (line.StartsWith("https")) { req = HttpWebRequest.Create(line); } } HttpWebRequest httpreq = (HttpWebRequest)req; httpreq.CookieContainer = new CookieContainer(); foreach (string line in youtubedlres.Split('\n')) { if (line.Contains(hsc)) { string[] jar = line.Substring(hsc.Length - 1).Split(' '); foreach (string cookie in jar) { if (cookie.Length > 2) { string[] cokie = cookie.Split('='); if (cokie.Length > 1 && (cokie[0] != "expires" && cokie[0] != "Expires")) { Cookie c**k = new Cookie(cokie[0], (cokie[1].EndsWith(";")) ? cokie[1].Substring(0, cokie[1].Length - 2) : cokie[1]); c**k.Domain = "youtube.com"; httpreq.CookieContainer.Add(c**k); } } } } } int vacIndex = -69; for (int i = 0; i < WaveOut.DeviceCount; i++) { WaveOutCapabilities cap = WaveOut.GetCapabilities(i); if (cap.ProductName.Contains("VB-Audio Virtual")) { vacIndex = i; } } if (vacIndex == -69) { throw new Exception("Couldn't find virtual audio cable device. Do you have it installed?"); } WaveOut waveOut = new WaveOut(); waveOut.DeviceNumber = vacIndex; //BufferedWaveProvider bufferedWaveProvider = new BufferedWaveProvider(WaveFormat.CreateALawFormat(bufstr.getAudioData().Item1, bufstr.getAudioData().Item2)); bufstr.setReadStream(httpreq.GetResponse().GetResponseStream()); //bufstr.setWriteStream(bufferedWaveProvider); StreamMediaFoundationReader streamread = new StreamMediaFoundationReader(bufstr.getStream(), new MediaFoundationReader.MediaFoundationReaderSettings() { SingleReaderObject = true }); waveOut.Init(streamread); waveOut.Play(); int secks = 0; while (secks < bufstr.approxlen) { while (waveOut.PlaybackState == PlaybackState.Playing) { secks++; Thread.Sleep(1000); //bufstr.readToStream(); if (secks % 30 > 10) { bufstr.readToStream(); } //if (waveOut.PlaybackState == PlaybackState.Stopped) waveOut.Play(); } waveOut.Play(); } }
/// <summary> /// Load Pixels from file /// </summary> /// <param name="path">Path to pixels file</param> /// <returns>Pixels</returns> public static Pixels LoadFromFile(string path) { Pixels ret = null; try { if (path != null) { if (File.Exists(path)) { PixelsDataContract pixels_data = null; using (ZipArchive archive = ZipFile.Open(path, ZipArchiveMode.Read)) { try { ZipArchiveEntry entry = archive.GetEntry("meta.json"); if (entry != null) { using (Stream stream = entry.Open()) { pixels_data = serializer.ReadObject(stream) as PixelsDataContract; } } if (pixels_data != null) { Dictionary <string, JavascriptContext> scripts = new Dictionary <string, JavascriptContext>(); Dictionary <string, Image> sprites = new Dictionary <string, Image>(); Dictionary <string, WaveOut> sounds = new Dictionary <string, WaveOut>(); foreach (PixelsAssetDataContract asset in pixels_data.Assets) { try { if (asset != null) { EPixelsAssetType pixels_asset_type; if (Enum.TryParse(asset.Type, out pixels_asset_type)) { entry = archive.GetEntry(asset.Entry); if (entry != null) { switch (pixels_asset_type) { case EPixelsAssetType.Script: using (StreamReader reader = new StreamReader(entry.Open())) { JavascriptContext context = new JavascriptContext(); context.SetParameter("pixels", new { path, entry = Path.GetFileNameWithoutExtension(asset.Entry) }); context.Run(reader.ReadToEnd()); scripts.Add(Path.GetFileNameWithoutExtension(asset.Entry), context); } break; case EPixelsAssetType.Sprite: using (Stream stream = entry.Open()) { Image image = Image.FromStream(stream); if (image != null) { sprites.Add(Path.GetFileNameWithoutExtension(asset.Entry), image); } } break; case EPixelsAssetType.Sound: using (StreamMediaFoundationReader reader = new StreamMediaFoundationReader(entry.Open())) { WaveOut wave_out = new WaveOut(WaveCallbackInfo.FunctionCallback()); wave_out.Init(reader); sounds.Add(Path.GetFileNameWithoutExtension(asset.Entry), wave_out); } break; } } } else { Console.Error.WriteLine("Pixels asset type \"" + asset.Type + "\" is invalid."); } } } catch (Exception e) { Console.Error.WriteLine(e.Message); } } ret = new Pixels(scripts, sprites, sounds); } } catch (Exception e) { Console.Error.WriteLine(e.Message); } } } } } catch (Exception e) { Console.Error.WriteLine(e.Message); } return(ret); }
private static void WriteNormalizedAudio(string path, byte[] data) { using (var reader = new StreamMediaFoundationReader(new MemoryStream(data))) WriteNormalizedAudio(path, reader); }
public BackgroundWorker SendAudio(string url, IAudioClient vClient) { #region Get video stream MemoryStream ms = new MemoryStream(); bool running = true; object msLock = new object(); //new Thread(delegate (object o) //{ try { var response = WebRequest.Create(url).GetResponse(); using (var stream = response.GetResponseStream()) { byte[] gettingBuffer = new byte[65536]; // 64KB chunks int read; while ((read = stream.Read(gettingBuffer, 0, gettingBuffer.Length)) > 0) { lock (msLock) { // var pos = ms.Position; // ms.Position = ms.Length; ms.Write(gettingBuffer, 0, read); // ms.Position = pos; } } } running = false; } catch (Exception ex) { Console.WriteLine(ex.Message); } // }).Start(); // Pre-buffering some data to allow NAudio to start playing // while (ms.Length < 65536 * 10 && running) // Thread.Sleep(1000); ms.Position = 0; #endregion var channelCount = client.GetService <AudioService>().Config.Channels; // Get the number of AudioChannels our AudioService has been configured to use. var OutFormat = new WaveFormat(48000, 16, channelCount); // Create a new Output Format, using the spec that Discord will accept, and with the number of channels that our client supports. BackgroundWorker worker = new BackgroundWorker(); worker.WorkerSupportsCancellation = true; using (var StreamFileReader = new StreamMediaFoundationReader(ms)) // Create a new Disposable MP3FileReader, to read audio from the filePath parameter using (var resampler = new MediaFoundationResampler(StreamFileReader, OutFormat)) // Create a Disposable Resampler, which will convert the read MP3 data to PCM, using our Output Format { resampler.ResamplerQuality = 60; // Set the quality of the resampler to 60, the highest quality int blockSize = OutFormat.AverageBytesPerSecond / 50; // Establish the size of our AudioBuffer byte[] buffer = new byte[blockSize]; int byteCount = 0; worker.DoWork += new DoWorkEventHandler((object sender, DoWorkEventArgs e) => { try { do { lock (msLock) byteCount = resampler.Read(buffer, 0, blockSize); // Read audio into our buffer, and keep a loop open while data is present if (byteCount < blockSize) { // Incomplete Frame for (int i = byteCount; i < blockSize; i++) { buffer[i] = 0; } } vClient.Send(buffer, 0, blockSize); // Send the buffer to Discord }while (!worker.CancellationPending && (byteCount > 0 || running)); ms.Close(); ms.Dispose(); } catch (Exception ex) { Console.WriteLine(ex.Message); } }); worker.RunWorkerAsync(); } return(worker); }
public void Initialize() { Process process = new Process(); ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; startInfo.FileName = "cmd.exe"; startInfo.Arguments = "/C youtube-dl --get-url --print-traffic -f 249 https://youtube.com/watch?v=SuperDuperFunUrl"; process.StartInfo = startInfo; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.Start(); process.WaitForExit(); string hsc = "header: Set-Cookie:"; WebRequest req = HttpWebRequest.Create("http://www.retardedispsayswhat.net"); string youtubedlres = process.StandardOutput.ReadToEnd(); foreach (string line in youtubedlres.Split('\n')) { if (line.StartsWith("https")) { req = HttpWebRequest.Create(line); } } HttpWebRequest httpreq = (HttpWebRequest)req; httpreq.CookieContainer = new CookieContainer(); foreach (string line in youtubedlres.Split('\n')) { if (line.Contains(hsc)) { string[] jar = line.Substring(hsc.Length - 1).Split(' '); foreach (string cookie in jar) { if (cookie.Length > 2) { string[] cokie = cookie.Split('='); if (cokie.Length > 1 && cokie[0] != "expires") { Cookie c**k = new Cookie(cokie[0], (cokie[1].EndsWith(";")) ? cokie[1].Substring(0, cokie[1].Length - 2) : cokie[1]); c**k.Domain = "youtube.com"; httpreq.CookieContainer.Add(c**k); } } } } } int vacIndex = -69; for (int i = 0; i < WaveOut.DeviceCount; i++) { WaveOutCapabilities cap = WaveOut.GetCapabilities(i); if (cap.ProductName.Contains("VB-Audio Virtual")) { vacIndex = i; } } if (vacIndex == -69) { throw new Exception("Couldn't find virtual audio cable device. Do you have it installed?"); } WaveOut waveOut = new WaveOut(); waveOut.DeviceNumber = vacIndex; WebResponse response = httpreq.GetResponse(); Stream stream = response.GetResponseStream(); long len = response.ContentLength; byte[] b = new byte[len]; byte[] p = null; Console.WriteLine("Caching shit"); MemoryStream ns = new MemoryStream(); //new Thread(new ParameterizedThreadStart(pissoff)).Start((object)(b, ms,stream)); int count = 0; do { byte[] buf = new byte[4096]; count = stream.Read(buf, 0, 4096); ns.Write(buf, 0, count); } while (stream.CanRead && count > 0); p = ns.ToArray(); Console.WriteLine("playing it"); MemoryStream ms = new MemoryStream(b); bool fookinequal = ms.ToArray().SequenceEqual(ns.ToArray()); StreamMediaFoundationReader streamread = new StreamMediaFoundationReader(ns); waveOut.Init(streamread); waveOut.Play(); while (waveOut.PlaybackState == PlaybackState.Playing) { Thread.Sleep(1000); } }