/// <summary> /// 再生を開始します。 /// </summary> public void PlayStreaming(string url) { if (_waveOut == null) { new Thread(delegate(object o) { var response = WebRequest.Create(url).GetResponse(); using (var stream = response.GetResponseStream()) { byte[] buffer = new byte[65536]; // 64KB chunks int read; while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) { var pos = ms.Position; ms.Position = ms.Length; ms.Write(buffer, 0, read); ms.Position = pos; } } }).Start(); } // Pre-buffering some data to allow NAudio to start playing while (ms.Length < 65536 * 10) { Thread.Sleep(1000); } int errorCont = 0; try { using (reader = new Mp3FileReader(ms)) using (WaveStream pcm = WaveFormatConversionStream.CreatePcmStream(reader)) using (WaveStream blockAlignedStream = new BlockAlignReductionStream(pcm)) { using (_waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback())) { _waveOut.Init(blockAlignedStream); _waveOut.Play(); while (_waveOut.PlaybackState == PlaybackState.Playing) { Console.WriteLine(reader.CurrentTime); System.Threading.Thread.Sleep(100); } } } } catch { if (errorCont > 10) { MessageBox.Show("10回Tryしましたが再生に失敗しました。"); } errorCont++; } }
private void CreateWaveOut() { CloseWaveOut(); int latency = (int)comboBoxLatency.SelectedItem; if (radioButtonWaveOut.Checked) { WaveCallbackInfo callbackInfo = checkBoxWaveOutWindow.Checked ? WaveCallbackInfo.NewWindow() : WaveCallbackInfo.FunctionCallback(); WaveOut outputDevice = new WaveOut(callbackInfo); outputDevice.DesiredLatency = latency; waveOut = outputDevice; } else if (radioButtonDirectSound.Checked) { waveOut = new DirectSoundOut(latency); } else if (radioButtonAsio.Checked) { waveOut = new AsioOut((String)comboBoxAsioDriver.SelectedItem); buttonControlPanel.Enabled = true; } else { waveOut = new WasapiOut( checkBoxWasapiExclusiveMode.Checked ? AudioClientShareMode.Exclusive : AudioClientShareMode.Shared, checkBoxWasapiEventCallback.Checked, latency); } }
/// <summary> /// mp3 /// </summary> public AudioFileTimeSource(string path, string device) { _path = path; switch (Path.GetExtension(path).ToUpper().TrimStart('.')) { case "MP3": _rdr = new Mp3FileReader(path); break; case "WAV": _rdr = new WaveFileReader(path); break; default: throw new ArgumentException($"Unsupported Audio file format", nameof(path)); } _wavStream = WaveFormatConversionStream.CreatePcmStream(_rdr); _baStream = new BlockAlignReductionStream(_wavStream); _waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()); _waveOut.DeviceNumber = GetDeviceNumber(device); _waveOut.DesiredLatency = 150; _waveOut.Init(_baStream); }
void StartEncoding() { _startTime = DateTime.Now; _bytesSent = 0; _segmentFrames = 960; var channels = 1; _encoder = Codec.OpusEncoder.Create(48000, channels, Codec.Opus.Application.Voip); _encoder.Bitrate = 8192; _decoder = Codec.OpusDecoder.Create(48000, channels); _bytesPerSegment = _encoder.FrameByteCount(_segmentFrames); _waveIn = new WaveIn(WaveCallbackInfo.FunctionCallback()); _waveIn.BufferMilliseconds = 50; _waveIn.DeviceNumber = comboBox1.SelectedIndex; _waveIn.DataAvailable += _waveIn_DataAvailable; _waveIn.WaveFormat = new WaveFormat(48000, 16, channels); _playBuffer = new BufferedWaveProvider(new WaveFormat(48000, 16, channels)); _waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()); _waveOut.DeviceNumber = comboBox2.SelectedIndex; _waveOut.Init(_playBuffer); _waveOut.Play(); _waveIn.StartRecording(); if (_timer == null) { _timer = new Timer(); _timer.Interval = 1000; _timer.Tick += _timer_Tick; } _timer.Start(); }
public void PlayMp3FromUrl(string url, int timeout) { 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(timeout); waiting = false; } } } }
//Functionality that plays the passed stream back to the user. //This will "freeze" the UI untill playback is completed. //INPUT: memoryStream //OUTPUT: Function result public functionResult onPlayback(ref Stream ms) { functionResult result = new functionResult(); try { //Go to position 0 of the audio stream ms.Position = 0; //Conver the stream to a wavefile and create the required heades using (WaveStream blockAlignedStream = new BlockAlignReductionStream(WaveFormatConversionStream.CreatePcmStream(new WaveFileReader(ms)))) { using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback())) { //Start playing waveOut.Init(blockAlignedStream); waveOut.Play(); //While we are playing, prevent anything from happenign on the UI. Might be worth expanding this to have a "Stop" button while (waveOut.PlaybackState == PlaybackState.Playing) { System.Threading.Thread.Sleep(100); } } } result.Result = true; result.Message = "onPlayback - OK"; } catch (Exception ex) { result.Result = false; result.Message = "ERROR - onPlayback - " + ex.ToString(); } return(result); }
public void PlaySound(string name, Action done = null) { FileStream ms = File.OpenRead(_soundLibrary[name]); var rdr = new Mp3FileReader(ms); WaveStream wavStream = WaveFormatConversionStream.CreatePcmStream(rdr); var baStream = new BlockAlignReductionStream(wavStream); var waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()); waveOut.Init(baStream); waveOut.Play(); var bw = new BackgroundWorker(); bw.DoWork += (s, o) => { while (waveOut.PlaybackState == PlaybackState.Playing) { Thread.Sleep(100); } waveOut.Dispose(); baStream.Dispose(); wavStream.Dispose(); rdr.Dispose(); ms.Dispose(); if (done != null) { done(); } }; bw.RunWorkerAsync(); }
void play() { if (!this.initialized) { this.Init(); } if (!this.initialized) { return; } if (this.waveOut != null) { this.waveOut.PlaybackStopped -= WaveOut_PlaybackStopped; this.waveOut.Stop(); this.waveOut.Dispose(); this.waveOut = null; } this.Content.SetPosition(0); this.waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()); this.waveOut.Init(blockAlignedStream); this.waveOut.PlaybackStopped += WaveOut_PlaybackStopped; this.waveOut.Play(); this.timer.Start(); }
public void DownloadFile(string urlAddress, string location) { using (webClient = new WebClient()) { try { Uri URL = new Uri(urlAddress); // Start downloading the file webClient.DownloadFile(URL, location); using (FileStream memoryStream = File.OpenRead(location)) { memoryStream.Position = 0; using ( WaveStream blockAlignedStream = new BlockAlignReductionStream(WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(memoryStream)))) { using (_waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback())) { _waveOut.Init(blockAlignedStream); _waveOut.Play(); while (_waveOut.PlaybackState == PlaybackState.Playing) { Thread.Sleep(100); } _waveOut.Stop(); _waveOut.Dispose(); } } } } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
private void PlayMp3(string url) { try { Stream ms = new MemoryStream(); // 设置参数 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; //发送请求并获取相应回应数据 HttpWebResponse response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 Stream responseStream = response.GetResponseStream(); byte[] buffer = new byte[1024]; int size = 0; //size是读入缓冲区中的总字节数。 如果当前可用的字节数没有请求的字节数那么多,则总字节数可能小于请求的字节数,或者如果已到达流的末尾,则为零 (0)。 while ((size = responseStream.Read(buffer, 0, buffer.Length)) != 0) //将responseStream的内容读入buffer数组 { ms.Write(buffer, 0, size); //将buffer数组的内容写入内存流ms } responseStream.Close(); //关闭流并释放连接以供重用 ms.Position = 0; //将内存流数据读取位置归零 WaveStream blockAlignedStream = new BlockAlignReductionStream(WaveFormatConversionStream.CreatePcmStream(new Mp3FileReader(ms))); WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()); waveOut.Init(blockAlignedStream); //waveOut.PlaybackStopped += (sender, e) => { waveOut.Stop(); }; waveOut.Play(); while (waveOut.PlaybackState == PlaybackState.Playing) { Thread.Sleep(100); } } catch (Exception ex) { ex.Message.ToString(); } }
// ------ Wave Player Methods ------ // Creates the wave player. The wave provider is required to initialize the wave player. // Wave players created through this method should be released by the ReleaseWavePlayer method. private IWavePlayer CreateWavePlayer(IWaveProvider waveProvider) { IWavePlayer player = new WaveOut(WaveCallbackInfo.FunctionCallback()); player.Init(waveProvider); return(player); }
public WzMp3Streamer(WzBinaryProperty sound, bool repeat) { this.repeat = repeat; this.sound = sound; byteStream = new MemoryStream(sound.GetBytes(false)); this.bIsMP3File = !sound.Name.EndsWith("wav"); // mp3 file does not end with any extension wavePlayer = new WaveOut(WaveCallbackInfo.FunctionCallback()); try { if (bIsMP3File) { mpegStream = new Mp3FileReader(byteStream); wavePlayer.Init(mpegStream); } else { waveFileStream = new WaveFileReader(byteStream); wavePlayer.Init(waveFileStream); } } catch (System.Exception e) { playbackSuccessfully = false; //InvalidDataException // Message = "Not a WAVE file - no RIFF header" } Volume = 0.5f; // default volume wavePlayer.PlaybackStopped += new EventHandler <StoppedEventArgs>(wavePlayer_PlaybackStopped); }
protected override SinkSourceMode driverConnect() { if (selectedDevice <= 0) { return(SinkSourceMode.Offline); } owner.logText(String.Format("Opening Audio Device {0}", devices[selectedDevice])); try { waveIn = new WaveIn(WaveCallbackInfo.FunctionCallback()); waveIn.WaveFormat = new WaveFormat(owner.sampleRate, 16, 2); waveIn.DeviceNumber = devindex[selectedDevice]; waveIn.DataAvailable += WaveIn_DataAvailable; waveIn.BufferMilliseconds = 25; // 1200 samples at 48 kHz setChannels(new RTIO[] { ioL, ioR }, null); waveIn.StartRecording(); owner.logText(String.Format("Device {0} open", devices[selectedDevice])); processingType = ProcessingType.SynchronousSource; return(SinkSourceMode.Online); } catch (Exception e) { owner.showLogWin(); owner.logText(e.Message); return(SinkSourceMode.Error); } }
public WzMp3Streamer(WzSoundProperty sound, bool repeat) { this.repeat = repeat; this.sound = sound; byteStream = new MemoryStream(sound.GetBytes(false)); wavePlayer = new WaveOut(WaveCallbackInfo.FunctionCallback()); try { mpegStream = new Mp3FileReader(byteStream); wavePlayer.Init(mpegStream); } catch (System.InvalidOperationException) { try { waveFileStream = new WaveFileReader(byteStream); wavePlayer.Init(waveFileStream); } catch (FormatException) { playbackSuccessfully = false; } //InvalidDataException } wavePlayer.PlaybackStopped += new EventHandler <StoppedEventArgs>(wavePlayer_PlaybackStopped); }
public void Stream(string url, bool async) { if (url == null) { return; } WaveOut WaveOutPlay = new WaveOut(WaveCallbackInfo.FunctionCallback()); WaveOutPlay.DeviceNumber = device; using (var ms = new MemoryStream()) using (var 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; // Play WaveStream bool wav = url.ToLower().EndsWith(".wav") || url.ToLower().EndsWith(".wma"); var reader = wav ? WaveFormatConversionStream.CreatePcmStream(new WaveFileReader(ms)) : (WaveStream) new Mp3FileReader(ms); RunSession(WaveOutPlay, reader, url); } WaveOutPlay.Dispose(); }
public void PlaySound(CachedSound sound) { switch (sound.Type) { case TYPE_SOURCE.FILE_LOCAL: AddMixerInput(new CachedSoundSampleProvider(sound)); break; case TYPE_SOURCE.FILE_MP3_ONLINE: using (MemoryStream mp3file = new MemoryStream(sound.AudioData_FILE_MP3_ONLINE)) { using (WaveStream blockAlignedStream = new BlockAlignReductionStream(WaveFormatConversionStream.CreatePcmStream( new Mp3FileReader(mp3file)))) { using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback())) { waveOut.Init(blockAlignedStream); waveOut.Play(); while (waveOut.PlaybackState == PlaybackState.Playing) { System.Threading.Thread.Sleep(100); } } } } break; } }
private void CreateWaveOut() { //CloseWaveOut(); switch (_output) { case Output.WaveOut: var callbackInfo = WaveCallbackInfo.FunctionCallback(); var outputDevice = new WaveOut(callbackInfo) { DesiredLatency = Latency }; waveOut = outputDevice; break; case Output.DirectSound: waveOut = new DirectSoundOut(Latency); break; case Output.Wasapi: waveOut = new WasapiOut(WasapiExclusiveMode?AudioClientShareMode.Exclusive:AudioClientShareMode.Shared, Latency); break; case Output.Asio: waveOut = new AsioOut(AsioDriverName); break; } }
private WaveOut CreatePlay(string file) { string ext = Path.GetExtension(file); if (file.EndsWith(".mp3")) { using (var reader = new Mp3FileReader(file)) { using (var waveStream = WaveFormatConversionStream.CreatePcmStream(reader)) { using (var blockStream = new BlockAlignReductionStream(waveStream)) { play = new WaveOut(WaveCallbackInfo.FunctionCallback()); play.Init(blockStream); } } } } System.Media.SoundPlayer else if (file.EndsWith(".wma")) { using (var reader = new WMAFileReader(file)) { using (var waveStream = WaveFormatConversionStream.CreatePcmStream(reader)) { using (var blockStream = new BlockAlignReductionStream(waveStream)) { play = new WaveOut(WaveCallbackInfo.FunctionCallback()); play.Init(blockStream); } } } } }
private void PlaySoundAsync(object parameter) { string fileName = (string)parameter; using (var archive = DataArchive.Open(Settings.Default.LegendLocation)) using (var stream = archive.GetEntry(fileName).Open()) { stream.Position = 0; using (var reader = new Mp3FileReader(stream)) using (var conversionStream = WaveFormatConversionStream.CreatePcmStream(reader)) using (var provider = new BlockAlignReductionStream(conversionStream)) using (var waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback())) { waveOut.Init(provider); waveOut.Play(); while (waveOut.PlaybackState == PlaybackState.Playing) { Thread.Sleep(100); } } } TogglePlayButtonEnabled(true); }
private void play_thread() { log("Record Thread Started"); func_gen fg = new func_gen(setup); fg.SetWaveFormat(48000, 1); wo = new WaveOut(WaveCallbackInfo.FunctionCallback()); wo.DeviceNumber = usedev; wo.Init(fg); wo.Play(); log("Playing started"); while (!killthread) { System.Threading.Thread.Sleep(50); /*fg.freq = freq; * fg.amp = amp; * fg.func = func; * fg.on = on; */ } wo.Stop(); log("Playing stopped"); }
private void PlayFromPlaylist(int index) { _fileStream = File.OpenRead(playList[index].Path); _reader = new Mp3FileReader(_fileStream); var wavStream = WaveFormatConversionStream.CreatePcmStream(_reader); _blockAlignStream = new BlockAlignReductionStream(wavStream); _waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()); _timeSpan = _reader.TotalTime; _waveOut.Volume = VolBar.Value * (float)0.01; ElapsedBar.Maximum = (int)_timeSpan.TotalSeconds; MusicNameLbl.Text = playList[index].Artist + " - " + playList[index].Title; string time = _reader.TotalTime.ToString(); time = time.Remove(time.LastIndexOf('.'), 8); MusicSizeLbl.Text = time; SetButton(); if (_isPlaying) { Thread tt = new Thread(t => PlayAudio()); tt.Start(); } }
/// <summary> /// Plays the audio in the given media and logs the audio transcription if available. /// </summary> /// <param name="sender"></param> /// <param name="mediaSegmentContent"></param> static void OnMediaSegmentProcessed(object sender, MediaSegmentContent mediaSegmentContent) { if (mediaSegmentContent.Transcription.NBest != null && mediaSegmentContent.Transcription.NBest.Count > 0) { Log(mediaSegmentContent.Transcription.NBest[0].Display); } else { Log(mediaSegmentContent.TranscriptionResult); } using (WaveOut waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback())) { waveOut.Init(mediaSegmentContent.Audio.BlockAlignReductionStream); waveOut.Play(); while (waveOut.PlaybackState == PlaybackState.Playing) { System.Threading.Thread.Sleep(100); } } mediaSegmentContent.Dispose(); }
public static 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.Play(); while (waveOut.PlaybackState == PlaybackState.Playing) { System.Threading.Thread.Sleep(100); } } } } }
public void TurnOn() { switch (WorkMode) { case Waveform.Sine: break; case Waveform.Sine_Dual: break; case Waveform.Sine_VarPhase: break; case Waveform.Square: break; case Waveform.File: using (var rdr = new AudioFileReader(WaveFile.FilePath)) using (var wavStream = WaveFormatConversionStream.CreatePcmStream(rdr)) using (var baStream = new BlockAlignReductionStream(wavStream)) using (var waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback())) { waveOut.Init(baStream); waveOut.Play(); while (waveOut.PlaybackState == PlaybackState.Playing) { Thread.Sleep(100); } } break; } }
private static IWavePlayer CreateWavePlayer() { var callbackInfo = WaveCallbackInfo.FunctionCallback(); var outputDevice = new WaveOut(callbackInfo); return(outputDevice); }
// ------------------------------------------ // CONSTRUCTOR // ------------------------------------------ public WSRSpeaker(int device) { this.device = device; this.WaveOutSpeech = new WaveOut(WaveCallbackInfo.FunctionCallback()); this.WaveOutSpeech.DeviceNumber = device; this.synthesizer = new SpeechSynthesizer(); this.synthesizer.SpeakCompleted += new EventHandler <SpeakCompletedEventArgs>(synthesizer_SpeakCompleted); // Enumerate Voices foreach (InstalledVoice voice in synthesizer.GetInstalledVoices()) { VoiceInfo info = voice.VoiceInfo; WSRConfig.GetInstance().logInfo("TTS", "[" + device + "]" + "Name: " + info.Name + " Culture: " + info.Culture); } // Select Voice String v = WSRConfig.GetInstance().voice; if (v != null && v.Trim() != "") { WSRConfig.GetInstance().logInfo("TTS", "[" + device + "]" + "Select voice: " + v); synthesizer.SelectVoice(v); } }
/// <summary> /// Se encarga de comenzar a reproducir una cancion desde un archivo local /// </summary> /// <param name="ruta">La ruta de la cancion a reproducir</param> private void ReproducirCancionSinConexion(string ruta) { try { DetenerRecepcionDeCancion(); _waveOutEvent.Stop(); _bufferCancion = new MemoryStream(File.ReadAllBytes(ruta)); _mp3Reader = new Mp3FileReader(_bufferCancion); _blockAlignedStream = new WaveChannel32(_mp3Reader); _waveOutEvent = new WaveOut(WaveCallbackInfo.FunctionCallback()); _waveOutEvent.Init(_blockAlignedStream); _estadoReproductor = EstadoReproductor.Reproduciendo; _seguidorDeEventosDelReproductor.Start(); _waveOutEvent.Play(); } catch (Exception ex) { new MensajeEmergente().MostrarMensajeError(ex.Message); _waveOutEvent.Stop(); OnCambioEstadoReproduccion?.Invoke(false); _seguidorDeEventosDelReproductor.Stop(); _estadoReproductor = EstadoReproductor.Detenido; if (_bufferCancion != null && _blockAlignedStream != null) { _bufferCancion.Dispose(); _blockAlignedStream.Dispose(); } } }
public void Play(string fileName, bool async) { if (fileName == null) { return; } if (fileName.StartsWith("http")) { Stream(fileName, async); return; } if (!File.Exists(fileName)) { return; } // Play WaveStream bool wav = fileName.ToLower().EndsWith(".wav") || fileName.ToLower().EndsWith(".wma"); var reader = wav ? WaveFormatConversionStream.CreatePcmStream(new WaveFileReader(fileName)) : (WaveStream) new Mp3FileReader(fileName); WaveOut WaveOutPlay = new WaveOut(WaveCallbackInfo.FunctionCallback()); WaveOutPlay.DeviceNumber = device; RunSession(WaveOutPlay, reader, fileName); WaveOutPlay.Dispose(); }
public AudioPlayer(DiscordVoiceConfig __config) { config = __config; callbackInfo = WaveCallbackInfo.FunctionCallback(); outputDevice = new WaveOut(callbackInfo); bufferedWaveProvider = new BufferedWaveProvider(new WaveFormat(48000, 16, config.Channels)); }
private void InputDeviceStart() { InputDeviceStop(); if (!devp_.InputEnable.Value) { return; } try { var dev_no = MicDeviceInfo.GetDeviceNo(devp_.InputDeviceId.Value); if (dev_no < 0) { return; } var dev_info = WaveIn.GetCapabilities(dev_no); wave_in_ = new WaveIn(WaveCallbackInfo.FunctionCallback()); wave_in_.DataAvailable += OnWaveIn_DataAvailable; wave_in_.DeviceNumber = dev_no; wave_in_.WaveFormat = new WaveFormat( (int)devp_.InputSamplingRate.Value, (int)devp_.InputBitsPerSample.Value, Math.Min((int)devp_.InputChannelNum.Value, dev_info.Channels)); /* 入力開始 */ wave_in_.StartRecording(); } catch { InputDeviceStop(); } }