private static WaveStream CreateInputStream(string fileName) { WaveChannel32 inputStream; WaveStream readerStream = null; if (fileName.EndsWith(".wav")) { readerStream = new WaveFileReader(fileName); } else if (fileName.EndsWith(".ogg")) { readerStream = new OggVorbisFileReader(fileName); } else { throw new InvalidOperationException("Unsupported extension"); } // Provide PCM conversion if needed if (readerStream.WaveFormat.Encoding != WaveFormatEncoding.Pcm) { readerStream = WaveFormatConversionStream.CreatePcmStream(readerStream); readerStream = new BlockAlignReductionStream(readerStream); } // Provide conversion to 16 bits if needed if (readerStream.WaveFormat.BitsPerSample != 16) { var format = new WaveFormat(readerStream.WaveFormat.SampleRate, 16, readerStream.WaveFormat.Channels); readerStream = new WaveFormatConversionStream(format, readerStream); } inputStream = new WaveChannel32(readerStream); return(inputStream); }
public void PlayMp3FromStream(Stream orig) { using (Stream ms = new MemoryStream()) { orig.Position = 0; orig.CopyTo(ms); ms.Position = 0; using (WaveStream blockAlignedStream = new BlockAlignReductionStream( WaveFormatConversionStream.CreatePcmStream( new Mp3FileReader(ms)))) { waveOut.Stop(); waveOut = new WaveOut(); int callbackdeviceID = -1; for (int i = 0; i < WaveOut.DeviceCount; i++) { if (WaveOut.GetCapabilities(i).ProductName == ApplicationSettings.CallbackDeviceID) { callbackdeviceID = i; } } waveOut.DeviceNumber = callbackdeviceID; waveOut.Init(blockAlignedStream); waveOut.Play(); while (waveOut.PlaybackState == PlaybackState.Playing) { System.Threading.Thread.Sleep(10); } } } }
public int LoadWav(string path) { if (!isInitialized) { Error("Trying to Load Wav format for uninitialized sound manager"); } for (int i = 0; i < managedSounds.Count; ++i) { if (managedSounds[i].path == path) { managedSounds[i].refCount += 1; return(i); } } int result = -1; using (WaveStream waveStream = WaveFormatConversionStream.CreatePcmStream(new WaveFileReader(path))) { result = LoadStream(waveStream); managedSounds[result].path = path; } return(result); }
static public Sound Read(byte[] source) { Sound result = new Sound(); string fileName = "tmp.wma"; File.WriteAllBytes(fileName, source); WMAFileReader fileReader = new WMAFileReader(fileName); File.Delete(fileName); using (WaveStream wavStream = WaveFormatConversionStream.CreatePcmStream(fileReader)) { int bytesToRead; // using a mux, we force all sounds to be 2 channels bytesToRead = (int)wavStream.Length; byte[] rawWaveData = new byte[bytesToRead]; int bytesRead = wavStream.Read(rawWaveData, 0, bytesToRead); result.SetSound(rawWaveData, wavStream.WaveFormat); } return(result); }
// Creation of the stream reading stream based on passed soundFILETypes private WaveStream CreateReaderStream(MemoryStream memStream, soundFILETypes typ) { WaveStream readerStream = null; if (typ == soundFILETypes.WAVE) { readerStream = new WaveFileReader(memStream); if (readerStream.WaveFormat.Encoding != WaveFormatEncoding.Pcm && readerStream.WaveFormat.Encoding != WaveFormatEncoding.IeeeFloat) { readerStream = WaveFormatConversionStream.CreatePcmStream(readerStream); readerStream = new BlockAlignReductionStream(readerStream); } } else if (typ == soundFILETypes.MP3) { readerStream = new WaveFileReader(memStream); } else if (typ == soundFILETypes.AIFF) { readerStream = new WaveFileReader(memStream); } return(readerStream); }
/// <summary> /// Creazione dello Stream di lettura dle file in ingresso in base al tipo di file /// </summary> /// <param name="fileName"></param> /// <returns></returns> private WaveStream CreateReaderStream(string fileName) { WaveStream readerStream = null; if (fileName.EndsWith(".wav", StringComparison.OrdinalIgnoreCase)) { readerStream = new WaveFileReader(fileName); if (readerStream.WaveFormat.Encoding != WaveFormatEncoding.Pcm && readerStream.WaveFormat.Encoding != WaveFormatEncoding.IeeeFloat) { readerStream = WaveFormatConversionStream.CreatePcmStream(readerStream); readerStream = new BlockAlignReductionStream(readerStream); } } else if (fileName.EndsWith(".mp3", StringComparison.OrdinalIgnoreCase)) { readerStream = new Mp3FileReader(fileName); } else if (fileName.EndsWith(".aiff")) { readerStream = new AiffFileReader(fileName); } return(readerStream); }
/// <summary> /// 根据文件播放 /// </summary> /// <param name="fPath">要播放的文件路径</param> public void PlayAsPath(string fPath) { try { waveIn.StopRecording(); using (var wfr = new WaveFileReader(fPath)) using (WaveStream wavStream = WaveFormatConversionStream.CreatePcmStream(wfr)) using (var baStream = new BlockAlignReductionStream(wavStream)) using (waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback())) { waveOut.Init(baStream); waveOut.Play(); while (waveOut.PlaybackState == PlaybackState.Playing) { Thread.Sleep(100); } } } catch (Exception ex) { LogHelper.WriteError(ex); } }
private void PlayMp3FromUrl(string url) { using (Stream ms = new MemoryStream()) { using (Stream stream = WebRequest.Create(url) .GetResponse().GetResponseStream()) { byte[] buffer = new byte[32768]; int read; while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } } ms.Position = 0; using (WaveStream blockAlignedStream = new BlockAlignReductionStream( WaveFormatConversionStream.CreatePcmStream( new Mp3FileReader(ms)))) { using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback())) { waveOut.Init(blockAlignedStream); waveOut.PlaybackStopped += (sender, e) => { waveOut.Stop(); }; waveOut.Play(); waiting = true; stop.WaitOne(10000); waiting = false; } } } }
void test_play_file_MP3_from_ByteArray(string url) { var mp3Bytes = File.ReadAllBytes(url); //using (var mp3Stream = new MemoryStream(mp3Bytes)) //{ // using (var mp3FileReader = new Mp3FileReader(mp3Stream)) // { // using (var wave32 = new WaveChannel32(mp3FileReader, 0.1f, 1f)) // { // using (var ds = new DirectSoundOut()) // { // ds.Init(wave32); // ds.Play(); // while (ds.PlaybackState == PlaybackState.Playing) // { // Thread.Sleep(1000); // } // } // } // } //} using (WaveStream blockAlignedStream = new BlockAlignReductionStream(WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(new MemoryStream(mp3Bytes))))) { using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback())) { waveOut.Init(blockAlignedStream); waveOut.Play(); while (waveOut.PlaybackState == PlaybackState.Playing) { System.Threading.Thread.Sleep(100); } } } }
public static AudioClip GetClipByType(byte[] data, SupportFormatType type) { try { MemoryStream memoryStream = new MemoryStream(data); WaveStream wave = null; switch (type) { case SupportFormatType.mp3: wave = new Mp3FileReader(memoryStream); break; case SupportFormatType.flac: wave = new FlacReader(memoryStream); break; //case SupportFormatType.wav: // wave = new WaveFileReader(memoryStream); // break; //case SupportFormatType.aiff: // wave = new AiffFileReader(memoryStream); // break; } WaveStream waveStream = WaveFormatConversionStream.CreatePcmStream(wave); WAV wav = new WAV(AudioMemStream(waveStream).ToArray()); Debug.Log(wav); AudioClip audioClip = AudioClip.Create(string.Format("{0}Sound", type.ToString()), wav.SampleCount, 1, wav.Frequency, false); audioClip.SetData(wav.LeftChannel, 0); return(audioClip); } catch (Exception e) { Debug.Log("NAudioPlayer.GetClipByType() Error:" + e.Message); return(null); } }
public static string Converter(string inPath) { using (WaveFileReader mpbacground = new WaveFileReader(inPath)) { using (WaveStream background = WaveFormatConversionStream.CreatePcmStream(mpbacground)) { using (var mixer = new WaveMixerStream32()) { mixer.AutoStop = true; var messageOffset = background.TotalTime; var background32 = new WaveChannel32(background); background32.PadWithZeroes = false; mixer.AddInputStream(background32); using (var wave32 = new Wave32To16Stream(mixer)) { var mp3Stream = ConvertWavToMp3(wave32); inPath = inPath.Split('.')[0] + ".mp3"; File.WriteAllBytes(inPath, mp3Stream.ToArray()); } } } } return(inPath); }
/// <summary> /// Load a pre-recorded WAV /// </summary> private void openToolStripMenuItem_Click(object sender, EventArgs e) { SetupChart(); OpenFileDialog open = new OpenFileDialog(); open.InitialDirectory = @"c:\users\chris\appdata\local\temp"; open.Filter = "Wave File (*.wav)|*.wav;"; if (open.ShowDialog() != DialogResult.OK) { return; } // This will almost certainly go south! ;) WaveFileReader waveFileReader = new WaveFileReader(open.FileName); Wave = new WaveFormatConversionStream(WaveFormat, WaveFormatConversionStream.CreatePcmStream(waveFileReader)); WaveToFloat = new Wave16ToFloatProvider(Wave); processToolStripMenuItem.Enabled = true; clearToolStripMenuItem.Enabled = true; startToolStripMenuItem.Enabled = false; stopToolStripMenuItem.Enabled = false; }
void Playback() { while (MemoryStream.Length < 65536) { Thread.Sleep(1000); } MemoryStream.Position = 0; using (WaveStream blockAlignedStream = new BlockAlignReductionStream(WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(MemoryStream)))) { using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback())) { Omv.State = "Playing:"; waveOut.Init(blockAlignedStream); waveOut.Play(); while (waveOut.PlaybackState == PlaybackState.Playing && !Omv.Close_stream) { Thread.Sleep(100); } } } }
/// <summary> /// Creates the reader stream, supporting all filetypes in the core NAudio library, /// and ensuring we are in PCM format /// </summary> /// <param name="fileName">File Name</param> private void CreateReaderStream(string fileName) { if (fileName.EndsWith(".wav", StringComparison.OrdinalIgnoreCase)) { readerStream = new WaveFileReader(fileName); if (readerStream.WaveFormat.Encoding != WaveFormatEncoding.Pcm && readerStream.WaveFormat.Encoding != WaveFormatEncoding.IeeeFloat) { readerStream = WaveFormatConversionStream.CreatePcmStream(readerStream); readerStream = new BlockAlignReductionStream(readerStream); } } else if (fileName.EndsWith(".mp3", StringComparison.OrdinalIgnoreCase)) { //readerStream = new Mp3FileReader(fileName); readerStream = new MediaFoundationReader(fileName); } else if (fileName.EndsWith(".ogg", StringComparison.OrdinalIgnoreCase)) { //readerStream = new Mp3FileReader(fileName); readerStream = new NAudio.Vorbis.VorbisWaveReader(fileName); } else if (fileName.EndsWith(".flac", StringComparison.OrdinalIgnoreCase)) { //readerStream = new Mp3FileReader(fileName); readerStream = new NAudio.Flac.FlacReader(fileName); } else if (fileName.EndsWith(".aiff")) { readerStream = new AiffFileReader(fileName); } else { // fall back to media foundation reader, see if that can play it readerStream = new MediaFoundationReader(fileName); } }
private WaveStream CreateInputStream() { WaveChannel32 inputStream; Stream stream = Subsonic.StreamSong(currentSong.id); // Try to move this filling of memory stream into the background... Stream ms = new MemoryStream(); byte[] buffer = new byte[32768]; int read; while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) { playerThread.ReportProgress(50); ms.Write(buffer, 0, read); } ms.Position = 0; WaveStream mp3Reader = new Mp3FileReader(ms); WaveStream pcmStream = WaveFormatConversionStream.CreatePcmStream(mp3Reader); WaveStream blockAlignedStream = new BlockAlignReductionStream(pcmStream); inputStream = new WaveChannel32(blockAlignedStream); // we are not going into a mixer so we don't need to zero pad //((WaveChannel32)inputStream).PadWithZeroes = false; volumeStream = inputStream; //var meteringStream = new MeteringStream(inputStream, inputStream.WaveFormat.SampleRate / 10); //meteringStream.StreamVolume += new EventHandler<StreamVolumeEventArgs>(meteringStream_StreamVolume); return(volumeStream); }
private void _PlayFromUrl(string url) { using (Stream ms = new MemoryStream()) { using (Stream str = WebRequest.Create(url).GetResponse().GetResponseStream()) { byte[] buffer = new byte[600000]; int read; while ((read = str.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } } Playing = true; SoundTag = url; ms.Position = 0; using (WaveStream blockAlignedStream = new BlockAlignReductionStream( WaveFormatConversionStream.CreatePcmStream( new Mp3FileReader(ms)))) { using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback())) { waveOut.Init(blockAlignedStream); waveOut.Play(); while (waveOut.PlaybackState == PlaybackState.Playing) { SpinWait.SpinUntil(() => !Playing); break; } } } } }
private void ConvertToOgg(string uri, string fileLocation, string FileName) { MediaFoundationReader reader = new MediaFoundationReader(uri); WaveFormat newFormat = new WaveFormat(48000, reader.WaveFormat.Channels); WaveFormatConversionStream newStream = new WaveFormatConversionStream(newFormat, reader); WaveStream conv = WaveFormatConversionStream.CreatePcmStream(newStream); byte[] bytes = new byte[conv.Length]; conv.Position = 0; conv.Read(bytes, 0, (int)conv.Length); OpusEncoder encoder = OpusEncoder.Create(48000, 2, OpusApplication.OPUS_APPLICATION_AUDIO); var memo = new MemoryStream(); var oggOut = new OpusOggWriteStream(encoder, memo); var shorts = ByteToShort(bytes); oggOut.WriteSamples(shorts, 0, shorts.Count()); oggOut.Finish(); var result = memo.ToArray(); using (var stream = new FileStream(fileLocation + FileName, FileMode.Create)) { stream.Write(result, 0, result.Length); } }
async Task _SoundCloudStream(MessageEventArgs e, string[] Args, ulong ServerLight, Channel testout) { string temp = Args[1]; for (int i = 3; i < Args.Count(); i++) { temp += " " + Args[i]; } trackResults SCTracks = await SCClient.SearchTrack(temp); int j = 0; while (j < SCTracks.Count && SCTracks[j]?.streamable == false) { j++; } if (j < SCTracks.Count) { Stream OS = new MemoryStream(); Stream S = await SCClient.GetStream(SCTracks[j].id, _DiscordClient.GetService <AudioService>().Config.Channels); using (WaveStream waveStream = WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(S))) using (WaveFileWriter waveFileWriter = new WaveFileWriter(OS, waveStream.WaveFormat)) { byte[] bytes = new byte[waveStream.Length]; waveStream.Position = 0; waveStream.Read(bytes, 0, (int)OS.Length); waveFileWriter.Write(bytes, 0, bytes.Length); waveFileWriter.Flush(); } await SendAudioBuffer(ServerLight, testout, OS); S.Dispose(); OS.Dispose(); } }
public async Task PlayMp3FromUrl(string url, bool withTimer = true) { AudioUrl = url; Stream ms = new MemoryStream(); Stream stream = WebRequest.Create(url).GetResponse().GetResponseStream(); byte[] buffer = new byte[32768]; int read; Application.UseWaitCursor = true; await Task.Run(() => { while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } }); Application.UseWaitCursor = false; stream.Close(); ms.Position = 0; WaveStream blockAlignedStream = new BlockAlignReductionStream(WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(ms))); WaveOut.Init(blockAlignedStream); WaveOut.Play(); if (withTimer) { StopAudioTimer.Start(); } while (WaveOut.PlaybackState == PlaybackState.Playing) { await Task.Delay(100); } blockAlignedStream.Close(); ms.Close(); }
//This function will save the passed audio stream to the file name specified. This wills save in the same directory as the application //INPUT: memory stream, Filename //OUPUT: FunctionResult public functionResult onSaveFile(ref Stream ms, string filename) { functionResult result = new functionResult(); try { //Reset the audio stream position to 0, and save it to a new file. ms.Position = 0; using (WaveStream pcmStream = WaveFormatConversionStream.CreatePcmStream(new WaveFileReader(ms))) { //step 3: write wave data into file with WaveFileWriter. WaveFileWriter.CreateWaveFile(filename, pcmStream); } result.Result = true; result.Message = "onSaveFile - ok"; } catch (Exception ex) { result.Result = false; result.Message = "ERROR - onSaveFile - " + ex.ToString(); } return(result); }
/*public void volumeChange(int cmd) // 0 == stop || 1 == up || 2 == down * { * switch (cmd) * { * case 0: * if (volumeChangeThread != null) * volumeChangeThread.Suspend(); * volumeChangeThread = null; * break; * case 1: * volumeChangeThread = new System.Threading.Thread(() => * { * volumeLevel += 0.01F; * * }); * } * }*/ public void PlaySound(string pathToSong) { Logger.Info("st1"); lock (lockObject) { Logger.Info("st2"); DisposeWave(); Logger.Info("st3"); WaveStream pcm = WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(pathToSong)); Logger.Info("st3.1 " + pathToSong); stream = new BlockAlignReductionStream(pcm); Logger.Info("st3.2"); output = new WaveOut(); Logger.Info("st4 " + deviceNumber.ToString()); //output.DeviceNumber = deviceNumber; Logger.Info("st5"); output.Init(stream); Logger.Info("st6"); output.Play(); } Logger.Info("playing " + pathToSong); Logger.Info("playing to " + deviceNumber.ToString()); output.PlaybackStopped += output_PlaybackStopped; }
//play or pause the selected mp3 private void playButton_Click(object sender, EventArgs e) { if (this.mp3FilePath == null || this.mp3FilePath == "") { return; } if (output != null) { if (output.PlaybackState == PlaybackState.Playing) { output.Pause(); Console.WriteLine("Paused"); } else if (output.PlaybackState == PlaybackState.Paused) { output.Play(); Console.WriteLine("Played"); } } if (output == null) { WaveStream pcm = WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(this.mp3FilePath)); if (pcm == null) { return; } waveViewer1.WaveStream = pcm; stream = new BlockAlignReductionStream(pcm); output = new DirectSoundOut(); output.Init(stream); output.Play(); } }
private void sbtOpen_Click(object sender, EventArgs e) { sbtPause.Enabled = true; sbtPause.Focus(); OpenFileDialog open = new OpenFileDialog(); open.InitialDirectory = txtPathSave.Text; open.Filter = "MP3/WAV File (*.mp3,*.wav)|*.mp3;*.wav"; if (open.ShowDialog() != DialogResult.OK) { return; } DisposWave(); if (open.FileName.EndsWith(".mp3")) { WaveStream pcm = WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(open.FileName)); steam = new BlockAlignReductionStream(pcm); } else if (open.FileName.EndsWith(".wav")) { WaveStream pcm = new WaveChannel32(new WaveFileReader(open.FileName)); steam = new BlockAlignReductionStream(pcm); } else { throw new InvalidOperationException("ko phai file audio"); } txtTenFile.Text = open.SafeFileName; output = new DirectSoundOut(); output.Init(steam); output.Play(); }
private async Task <(List <HashedFingerprint> hashedFingerprints, TrackInfo track)> ToWaveAndTrack(string file) { await using var mp3 = new Mp3FileReader(file); await using var pcm = WaveFormatConversionStream.CreatePcmStream(mp3); var filename = Path.GetFileName(file); var outputFile = Path.Combine(_tempDir, filename + ".wav"); WaveFileWriter.CreateWaveFile(outputFile, pcm); var hashedFingerprints = await FingerprintCommandBuilder.Instance .BuildFingerprintCommand() .From(outputFile) .WithFingerprintConfig(new HighPrecisionFingerprintConfiguration()) .UsingServices(_audioService) .Hash(); var tag = TagLib.File.Create(file); var track = new TrackInfo(Guid.NewGuid().ToString(), tag.Tag.Title, tag.Tag.Performers.First(), mp3.Length); File.Delete(outputFile); return(hashedFingerprints, track); }
public void load_file_data(string file) { if (File.Exists(file)) {//Get File Data if (Path.GetExtension(file) != ".wav") { string _outPath_ = file.Replace(Path.GetExtension(file), ".wav"); using (Mp3FileReader mp3 = new Mp3FileReader(file)) { using (WaveStream pcm = WaveFormatConversionStream.CreatePcmStream(mp3)) { WaveFileWriter.CreateWaveFile(_outPath_, pcm); } } file = file.Replace(Path.GetExtension(file), ".wav"); } string displayName = Path.GetFileName(file); btn_player.Text = displayName; this.file = file; } }
private void FileOpener(object sender, EventArgs e) { //open a new file, ready to operate! OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "Supported Audio Files|*.ogg;*.wav;*.mp3|OGG Files (.ogg)|*.ogg|WAV Files (wav)|*.wav|MP3 Files|*.mp3"; dialog.FilterIndex = lastFormatOpened + 1; DialogResult respuesta = dialog.ShowDialog(); lastFormatOpened = (sbyte)(dialog.FilterIndex - 1); if (respuesta == DialogResult.OK) { if (vorb != null) { vorb.Dispose(); } if (wove != null) { wove.Dispose(); } waveOut.Dispose(); currentFile = dialog.FileName; //OGG if (dialog.FileName.Substring((dialog.FileName.Length - 4), 4).ToUpperInvariant() == formatList[(int)formats.ogg].ToUpperInvariant()) { try { archivoActual = dialog.OpenFile(); var v = new VorbisReader(archivoActual, true); sampleRate = v.SampleRate; sampleTotal = v.TotalSamples; channels = (byte)v.Channels; string[] tags = v.Comments; string tagTITLE = ""; //seek tags here. tagTITLE = tagSeeker.getOggTagValue(v.Comments, "TITLE"); if (tagTITLE != "") { audioView.Text = tagTITLE; } else { audioView.Text = dialog.SafeFileName; } sampleStart = Convert.ToInt64(tagSeeker.getOggTagValue(v.Comments, "LOOPSTART", true)); sampleLength = Convert.ToInt64(tagSeeker.getOggTagValue(v.Comments, "LOOPLENGTH", true)); vorb = new NAudio.Vorbis.VorbisWaveReader(dialog.FileName); wove = new LoopWAV(vorb); wove.loopstart = (long)(((float)sampleStart / (float)sampleRate) * ((float)wove.Length / (((float)sampleTotal / (float)sampleRate))));//calculamos los bytes donde se regresa la música en base a los samples que tenemos. if (sampleLength > 0) { wove.looplength = ((long)(((float)(sampleLength + sampleStart) / (float)sampleRate) * ((float)wove.Length / (((float)sampleTotal / (float)sampleRate))))); } Console.WriteLine("SampleTotal:{0,2} SampleStart:{1,3} Calculated Start Byte: {2} Calculated Length Byte: {3} Bytes: {4}", sampleTotal, sampleStart, wove.loopstart, wove.looplength, wove.Length); waveOut.Init(wove); trackBar1.Maximum = (int)(((float)sampleTotal / (float)sampleRate) * 1000f); Console.WriteLine("track max: " + trackBar1.Maximum); label_AudioData.Text = String.Format("{0} Kbits {1} KHz {2} Channels", (v.NominalBitrate / 1000), ((float)sampleRate / 1000), (channels)); currentFormat = (int)formats.ogg; lastFormatOpened = (ushort)formats.ogg + 1; radioSamples_CheckedChanged(sender, e); enabler_main(true); } catch (Exception ouch) { MessageBox.Show("Error on loading OGG...\n" + ouch.ToString(), "Load error"); cerrarToolStripMenu_Click(sender, e); } } else if ((dialog.FileName.Substring((dialog.FileName.Length - 4), 4).ToUpperInvariant() == formatList[(int)formats.wav].ToUpperInvariant())) { //WAV archivoActual = dialog.OpenFile(); try { //wavs are diferent, I can get their (aproximate) total time so we use that instead. WaveFileReader temp = new WaveFileReader(archivoActual); wove = new LoopWAV(temp); waveOut = new WaveOutEvent(); waveOut.Init(wove); trackBar1.Maximum = (((int)wove.TotalTime.TotalSeconds) + 1) * 1000;//miliseconds precise? audioView.Text = ""; enabler_main(true); //MessageBox.Show("Loading a WAVe of sound!", "Incredibly LAME pun!"); label_AudioData.Text = waveOut.OutputWaveFormat.ToString(); audioView.Text = dialog.SafeFileName; currentFormat = (int)formats.wav; lastFormatOpened = (ushort)formats.wav + 1; Console.WriteLine("Samples: {0} \tLength(bytes): {1}", temp.SampleCount, temp.Length); } catch (Exception horror) { MessageBox.Show("Error on loading FILE...it was that bad of a file.\n\n" + horror.Message, "Load error"); cerrarToolStripMenu_Click(sender, e); } } else if ((dialog.FileName.Substring((dialog.FileName.Length - 4), 4).ToUpperInvariant() == formatList[(int)formats.mp3].ToUpperInvariant())) { try { //H4R0X the MP3 to make it a WAV instead! way to evade a LAME royalty ;-) //also it's easier to transform to OGG if the user desires. //IF I MANAGE TO TURN IT INTO AN OGG THAT IS!!! archivoActual = dialog.OpenFile(); Mp3FileReader rad = new Mp3FileReader(archivoActual); emp3 = WaveFormatConversionStream.CreatePcmStream(rad); wove = new LoopWAV(emp3); waveOut = new WaveOutEvent(); waveOut.Init(wove); trackBar1.Maximum = (((int)wove.TotalTime.TotalSeconds) + 1) * 1000;//miliseconds precise? currentFormat = (sbyte)formats.mp3; label_AudioData.Text = waveOut.OutputWaveFormat.ToString(); audioView.Text = dialog.SafeFileName; enabler_main(true); } catch (Exception horror) { MessageBox.Show("Error on loading FILE...\n\n" + horror.Message, "Load error"); cerrarToolStripMenu_Click(sender, e); } } else { MessageBox.Show("Wrong File tipe, how did you do that?", "You dirty hacker!"); } } else { //normally chech if error but nope, not for now. } dialog.Dispose(); }
public async Task Run([BlobTrigger("audio-workitems/{name}")] CloudBlockBlob myBlob, string name, ILogger log) { if (myBlob is null) { throw new ArgumentNullException(nameof(myBlob)); } if (name is null) { throw new ArgumentNullException(nameof(name)); } if (log is null) { throw new ArgumentNullException(nameof(log)); } BlobProperties properties = myBlob.Properties; if (properties.ContentType != "audio/mpeg") { return; } using var stream = await myBlob.OpenReadAsync().ConfigureAwait(false); using var mp3 = new Mp3FileReader(stream); using var pcm = WaveFormatConversionStream.CreatePcmStream(mp3); var wavFile = Path.GetTempFileName(); try { WaveFileWriter.CreateWaveFile(wavFile, pcm); using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(5)); using var audioInput = AudioConfig.FromWavFileInput(wavFile); using var recognizer = new SpeechRecognizer(_speechConfig, audioInput); var watch = Stopwatch.StartNew(); var results = new List <Phrase>(); var complete = new TaskCompletionSource <bool>(); recognizer.SpeechEndDetected += (o, e) => complete.TrySetResult(true); recognizer.Recognized += (o, e) => { var r = e.Result; var offset = TimeSpan.FromTicks(r.OffsetInTicks); log.LogInformation("Found phrase at: {offset} - '{text}'", offset, r.Text); results.Add(new Phrase { offset = offset, duration = r.Duration, text = r.Text, }); }; await Task.WhenAll( recognizer.StartContinuousRecognitionAsync(), complete.Task ).ConfigureAwait(false); await recognizer.StopContinuousRecognitionAsync().ConfigureAwait(false); } finally { File.Delete(wavFile); } }
public void PlayMp3FromUrl(string url) { new Thread(delegate(object o) { var request = (HttpWebRequest)WebRequest.Create(url); request.CookieContainer = cookie; request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko"; request.Method = "GET"; request.Accept = "text/html"; request.AllowAutoRedirect = true; request.Timeout = 15000; request.ReadWriteTimeout = 15000; try { var response = request.GetResponse(); using (var stream = response.GetResponseStream()) { var buffer = new byte[65536]; // 64KB chunks int read; while (stream != null && (read = stream.Read(buffer, 0, buffer.Length)) > 0) { var pos = _ms.Position; _ms.Position = _ms.Length; _ms.Write(buffer, 0, read); _ms.Position = pos; } } } catch (WebException) { Debug.WriteLine("Error retriving or playing stream"); if (SongComplete != null) { SongComplete(); } } }).Start(); // Pre-buffering some data to allow NAudio to start playing while (_ms.Length < 65536 * 10) { Thread.Sleep(1000); } _ms.Position = 0; try { using ( _blockAlignedStream = new BlockAlignReductionStream(WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(_ms))) ) { using (var waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback())) { waveOut.DeviceNumber = _device; waveOut.Init(_blockAlignedStream); waveOut.Play(); while (waveOut.PlaybackState != PlaybackState.Stopped) { if (GetVolume != null) { waveOut.Volume = GetVolume(); } // Debug.WriteLine(GetVolume()); if (_shouldStop) { waveOut.Stop(); } if (_isPaused) { waveOut.Pause(); } if (!_isPaused) { waveOut.Resume(); } if (waveOut.PlaybackState == PlaybackState.Playing) { Thread.Sleep(100); } SongCurrTime?.Invoke(_blockAlignedStream.CurrentTime.TotalSeconds); if (waveOut.PlaybackState == PlaybackState.Paused) { Thread.Sleep(1000); } } if (waveOut.PlaybackState == PlaybackState.Paused) { Debug.WriteLine("IM here 1"); } if (_shouldStop) { return; } Debug.WriteLine("IM here 2"); _shouldStop = false; waveOut.Stop(); waveOut.Dispose(); SongComplete?.Invoke(); } } } catch (Exception) { Debug.WriteLine("Error happend, moving to next song"); SongComplete?.Invoke(); } }
public void Play() { OptReturn optReturn; if (string.IsNullOrEmpty(mUrl)) { optReturn = new OptReturn(); optReturn.Code = Defines.RET_STRING_EMPTY; optReturn.Message = string.Format(("Url is empty")); ShowException(optReturn); return; } try { WaveStream reader; if (mUrl.StartsWith("http", StringComparison.InvariantCultureIgnoreCase)) { if (mUrl.EndsWith(".mp3", StringComparison.InvariantCultureIgnoreCase)) { reader = new Mp3NetworkStream(mUrl); } else { reader = new NetWorkWaveReader(mUrl); if (reader.WaveFormat.Encoding != WaveFormatEncoding.Pcm && reader.WaveFormat.Encoding != WaveFormatEncoding.IeeeFloat) { reader = WaveFormatConversionStream.CreatePcmStream(reader); reader = new BlockAlignReductionStream(reader); } } } else { if (mUrl.EndsWith(".mp3", StringComparison.InvariantCultureIgnoreCase)) { reader = new Mp3FileReader(mUrl); } else { reader = new WaveFileReader(mUrl); if (reader.WaveFormat.Encoding != WaveFormatEncoding.Pcm && reader.WaveFormat.Encoding != WaveFormatEncoding.IeeeFloat) { reader = WaveFormatConversionStream.CreatePcmStream(reader); reader = new BlockAlignReductionStream(reader); } } } if (mWaveStream != null) { mWaveStream.Dispose(); } mWaveStream = reader; OnPlayerEventEvent(Defines.EVT_MEDIAOPENED, mWaveStream.TotalTime); if (!CreateWaveImage(mWaveStream)) { return; } LbTotalTime = GetTimeString(mWaveStream.TotalTime); LbCurrentTime = "00:00:00"; if (mSliderPosition != null) { mSliderPosition.Minimum = 0; mSliderPosition.Maximum = mWaveStream.TotalTime.TotalSeconds; } if (!CreateWaveStream()) { return; } if (!CreateWaveOut()) { return; } if (mWaveOut != null) { mWaveOut.Play(); mTimer.Start(); OnPlayerEventEvent(Defines.EVT_PLAYBACKSTARTED, mUrl); } } catch (Exception ex) { optReturn = new OptReturn(); optReturn.Code = Defines.RET_FAIL; optReturn.Message = ex.Message; ShowException(optReturn); } }
public static void Main(string[] args) { if (args.Length == 0) { var assembly = Assembly.GetExecutingAssembly(); var resourceName = "ConsoleEchoPrintSharp.Resources.NIN-999999-11025.wav"; using (Stream stream = assembly.GetManifestResourceStream(resourceName)) using (BinaryReader reader = new BinaryReader(stream, System.Text.Encoding.ASCII)) { string chunkId = new string(reader.ReadChars(4)); UInt32 chunkSize = reader.ReadUInt32(); string riffType = new string(reader.ReadChars(4)); string fmtId = new string(reader.ReadChars(4)); UInt32 fmtSize = reader.ReadUInt32(); UInt16 formatTag = reader.ReadUInt16(); UInt16 channels = reader.ReadUInt16(); UInt32 samplesPerSec = reader.ReadUInt32(); UInt32 avgBytesPerSec = reader.ReadUInt32(); UInt16 blockAlign = reader.ReadUInt16(); UInt16 bitsPerSample = reader.ReadUInt16(); string dataID = new string(reader.ReadChars(4)); UInt32 dataSize = reader.ReadUInt32(); if (chunkId != "RIFF" || riffType != "WAVE" || fmtId != "fmt " || dataID != "data" || fmtSize != 16) { Console.WriteLine("Malformed WAV header"); return; } if (channels != 1 || samplesPerSec != 11025 || avgBytesPerSec != 22050 || blockAlign != 2 || bitsPerSample != 16 || formatTag != 1 || chunkSize < 48) { Console.WriteLine("Unexpected WAV format, need 11025 Hz mono 16 bit (little endian integers)"); return; } uint numberOfsamples = Math.Min(dataSize / 2, 330750); // max 30 seconds var pcmData = new Int16[numberOfsamples]; for (int i = 0; i < numberOfsamples; i++) { pcmData[i] = reader.ReadInt16(); } var echoPrint = new CodeGen(); Console.WriteLine(echoPrint.Generate(pcmData)); Console.WriteLine(""); Console.WriteLine("The above is the EchoPrint code for the song '999,999' by Nine Inch Nails."); Console.WriteLine("To generate codes for your own mp3s or wavs add them as parameters to "); Console.WriteLine("ConsoleEchoPrintSharp.exe in a command line or in the debug settings"); Console.WriteLine("or execution setting of the ConsoleEchoPrintSharp project."); Console.WriteLine("(mp3s only work on Windows, because NAudio depends on Msacm32.dll.)"); } } else { foreach (string audioFile in args) { if (audioFile.Length >= 4 && audioFile.Substring(audioFile.Length - 4).Equals(".wav", StringComparison.InvariantCultureIgnoreCase)) { using (WaveFileReader wav = new WaveFileReader(audioFile)) { using (WaveStream pcm = WaveFormatConversionStream.CreatePcmStream(wav)) { using (BinaryReader reader = new BinaryReader(pcm, System.Text.Encoding.ASCII)) { HandleFile(pcm, audioFile); } } } } else if (audioFile.Length >= 4 && audioFile.Substring(audioFile.Length - 4).Equals(".mp3", StringComparison.InvariantCultureIgnoreCase)) { try { using (Mp3FileReader mp3 = new Mp3FileReader(audioFile)) { using (WaveStream pcm = WaveFormatConversionStream.CreatePcmStream(mp3)) { HandleFile(pcm, audioFile); } } } catch (DllNotFoundException e) { Console.WriteLine("Sorry, a necessary dll is not found on your system. Here come the details:\r\n\r\n{0}", e); } }