public PianoSynth() { mixer = new WaveMixerStream32(); mixer.AutoStop = false; int i = 0; foreach (var note in noteFiles) { reader[i] = new WaveFileReader(note); offsetStream[i] = new WaveOffsetStream(reader[i]); channelSteam[i] = new WaveChannel32(offsetStream[i]); channelSteam[i].Position = channelSteam[i].Length; mixer.AddInputStream(channelSteam[i]); i++; } if (waveOutDevice == null) { waveOutDevice = new WaveOut {DeviceNumber = 0}; waveOutDevice.Init(mixer); waveOutDevice.Volume = 0; waveOutDevice.Play(); waveOutDevice.Volume = 100; } }
public bool Load(string path, Guid device) { var cext = path.GetExt(); _myWaveOut = new DirectSoundOut(device); try { _myWaveStream = _codecs.First(v => v.Extensions.Contains(cext)).CreateWaveStream(path); } catch { return false; } if (_myWaveStream == null) return false; if (_myWaveStream.WaveFormat.Channels == 2) { _myBalanceSampleProvider = new BalanceSampleProvider(_myWaveStream.ToSampleProvider()); _myVolumeSampleProvider = new VolumeSampleProvider(_myBalanceSampleProvider); _myBalanceSampleProvider.Pan = (float)Balance; } else _myVolumeSampleProvider = new VolumeSampleProvider(_myWaveStream.ToSampleProvider()); _myEqualizer = new Equalizer(_myVolumeSampleProvider, _equalizerBands) { Enabled = _enableEqualizer }; _myWaveOut.Init(_myEqualizer); _myWaveOut.PlaybackStopped += MyWaveOutOnPlaybackStopped; _myVolumeSampleProvider.Volume = (float)Volume; return true; }
/// <summary> /// Lejátszik egy .mp3 fájlt /// </summary> /// <param name="audioFile">.mp3 fájl</param> public static void playWave(string audioFile) { thread = new WaveOut(); stream = CreateInputStream(audioFile); thread.Init(stream); thread.Play(); }
private async void Play() { if (reader == null) { return; } if (player == null) { // Exclusive mode - fails with a weird buffer alignment error //player = new MediaElementOut(MediaElement); player = new WasapiOutRT(AudioClientShareMode.Shared, 200); player.PlaybackStopped += PlayerOnPlaybackStopped; } if (player.PlaybackState != PlaybackState.Playing) { reader.Seek(0, SeekOrigin.Begin); await player.Init(reader); player.Play(); StopCommand.IsEnabled = true; PauseCommand.IsEnabled = true; } }
public MainForm() { waveOutDevice = null; mainOutputStream = null; volumeStream = null; InitializeComponent(); }
private void CreateWaveOut() { CloseWaveOut(); int latency = 300; _waveOut = SelectedOutputAudioDeviceFactory.CreateDevice(latency); _waveOut.PlaybackStopped += OnPlaybackStopped; }
private void Connect(IPEndPoint endPoint, int inputDeviceNumber, INetworkChatCodec codec) { waveIn = new WaveIn(); waveIn.BufferMilliseconds = 50; waveIn.DeviceNumber = inputDeviceNumber; waveIn.WaveFormat = codec.RecordFormat; waveIn.DataAvailable += waveIn_DataAvailable; waveIn.StartRecording(); udpSender = new UdpClient(); udpListener = new UdpClient(); // To allow us to talk to ourselves for test purposes: // http://stackoverflow.com/questions/687868/sending-and-receiving-udp-packets-between-two-programs-on-the-same-computer udpListener.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); udpListener.Client.Bind(endPoint); udpSender.Connect(endPoint); waveOut = new WaveOut(); waveProvider = new BufferedWaveProvider(codec.RecordFormat); waveOut.Init(waveProvider); waveOut.Play(); connected = true; var state = new ListenerThreadState { Codec = codec, EndPoint = endPoint }; ThreadPool.QueueUserWorkItem(ListenerThread, state); }
private void play_Click(object sender, EventArgs e) { if (playlist.SelectedItems.Count>0) { id = fn.IndexOf(playlist.SelectedItem.ToString()); if (waveOutDevice.PlaybackState.ToString() != "Paused") { t.Stop(); stp(); audioFileReader = new AudioFileReader(fp[id]); waveOutDevice = new WaveOut(); waveOutDevice.Init(audioFileReader); trackbar.Maximum = (int)audioFileReader.TotalTime.TotalSeconds + 1; //deb.Items.Add(audioFileReader.TotalTime.Seconds.ToString()); audioFileReader.Volume = (float)vol.Value / 100; waveOutDevice.Play(); t.Start(); } else { waveOutDevice.Play(); t.Start(); } } }
public AudioPlaybackEngine(int sampleRate = 44100, int channelCount = 2) { outputDevice = new WaveOutEvent(); mixer = new MixingSampleProvider(WaveFormat.CreateIeeeFloatWaveFormat(sampleRate, channelCount)); mixer.ReadFully = true; outputDevice.Init(mixer); outputDevice.Play(); }
public Audio(string filename) { this.fileName = filename; waveOutDevice = new DirectSoundOut(50); mainOutputStream = CreateInputStream(filename); waveOutDevice.Init(mainOutputStream); isPlaying = false; }
public int PlayFile(string filename) { waveOutDevice = new WaveOut(); mainOutputStream = CreateInputStream(filename); waveOutDevice.Init(mainOutputStream); waveOutDevice.Play(); return 0; }
private void frmMain_FormClosing(object sender, FormClosingEventArgs e) { if (this._player.PlaybackState == PlaybackState.Playing) this._player.Stop(); this._player.Dispose(); this._player = null; }
private void Stop() { if (waveOut != null) { this.patternSequencer = null; waveOut.Dispose(); waveOut = null; } }
public AudioPlaya(string filename) { waveOutDevice = new WaveOut(); waveOutDevice.Init(stream = loadFromFile(filename)); waveOutDevice.PlaybackStopped += (object sender, StoppedEventArgs e) => { if (Finished != null) Finished(this); }; }
public void Dispose() { Stop(); if (playbackDevice != null) { playbackDevice.Dispose(); playbackDevice = null; } }
public Mp3Player() { _waveOutDevice = new WaveOut(); _waveOutDevice.PlaybackStopped += (sender, args) => { _ms.Dispose(); _mainOutputStream.Dispose(); }; }
public MainWindow() { InitializeComponent(); Termination = false; waveOutDevice = new WaveOut(); waveOutDevice.PlaybackStopped += WaveOutDevice_PlaybackStopped; Play_List.ItemsSource = upcoming; cFunctions = new Cloud.CloudFunctions(); }
public void PlaySong() { // Instantiate audio player waveOutDevice = new WaveOut(); // Set MP3 to play audioFileReader = new AudioFileReader(GetSong()); // Init device and call play waveOutDevice.Init(audioFileReader); waveOutDevice.Play(); }
private void CloseWaveOut() { _waveOut?.Stop(); if (_waveOut != null) { _waveOut.Dispose(); _waveOut = null; } }
public RadioStationMain(string baseFolder) { if (player == null) { player = new WaveOut(); player.PlaybackStopped += OnPlaybackStopped; } randomFileSelector = new RandomFileSelector(baseFolder); CurrentPlayingFileName = LoadRandomFile(); }
public Mp3Player(Sounds sound) { _resourceName = SoundsHelper.GetResourceName(sound); _waveOutDevice = new WaveOut(); _waveOutDevice.PlaybackStopped += (sender, args) => { _ms.Dispose(); _mainOutputStream.Dispose(); }; }
/// <summary> /// /// </summary> public AnimatorClient() { try { waveOutDevice = new NAudio.Wave.DirectSoundOut(); } catch (Exception driverCreateException) { throw new InvalidOperationException("Could not initialize audio player", driverCreateException); } }
public void Init(string waveFilePath) { // 4410 samples == 100 milliseconds int sampleRate = 44100; int blockSize = (int) (sampleRate * 0.15f); //6615; int channels = 2; vstStream = new VSTStream(sampleRate, channels, blockSize, this.plugins, waveFilePath); //blocksize 4410 samples gave stuttering? 6615 was perfect, 8820 was OK (small glitches)! playbackDevice = new WaveOut(WaveCallbackInfo.FunctionCallback()); playbackDevice.Init(vstStream); }
private void BeginPlayback(string filename) { Debug.Assert(this.wavePlayer == null); this.wavePlayer = CreateWavePlayer(); this.file = new AudioFileReader(filename); this.file.Volume = volumeSlider1.Volume; this.wavePlayer.Init(file); this.wavePlayer.PlaybackStopped += wavePlayer_PlaybackStopped; this.wavePlayer.Play(); EnableButtons(true); timer1.Enabled = true; // timer for updating current time label }
private void Play() { if (waveOut != null) { Stop(); } waveOut = new WaveOut(); this.patternSequencer = new DrumPatternSampleProvider(pattern); this.patternSequencer.Tempo = tempo; waveOut.Init(patternSequencer); waveOut.Play(); }
public override void Stage() { wavePlayer = new WaveOutEvent(); file = new AudioFileReader(_fileName); file.Volume = 1; wavePlayer.Init(file); wavePlayer.PlaybackStopped += new EventHandler<StoppedEventArgs>(PlaybackEnded); _currentStatus = Status.Staged; }
public frmMain() { InitializeComponent(); MemoryStream stream = new MemoryStream(Properties.Resources.music); this.channel = new SampleChannel(new Mp3FileReader(stream)); this.channel.Volume = 0.02f; this._player = new WaveOut() { DesiredLatency = 500 }; this._player.Init(this.channel); this._player.Play(); this._player.PlaybackStopped += _player_PlaybackStopped; }
//Кнопка "Плей" private void button_play_Click(object sender, EventArgs e) { button_stop.Enabled = true; timer.Start(); ind = 2; waveOutDevice = new WaveOut(); mainOutputStream = CreateInputStream(outputFilename); waveOutDevice.Init(mainOutputStream); waveOutDevice.Play(); button_play.Enabled = false; button_rec.Enabled = false; numeric.Enabled = false; }
private void BeginPlayback(string filename) { Debug.Assert(this.wavePlayer == null); this.wavePlayer = new WaveOutEvent(); this.file = new AudioFileReader(filename); this.fadeInOut = new FadeInOutSampleProvider(file); this.file.Volume = volumeSlider1.Volume; this.wavePlayer.Init(new SampleToWaveProvider(fadeInOut)); this.wavePlayer.PlaybackStopped += wavePlayer_PlaybackStopped; this.wavePlayer.Play(); EnableButtons(true); timer1.Enabled = true; // timer for updating current time label }
private void OnDisposed(object sender, EventArgs eventArgs) { if (wavePlayer != null) { wavePlayer.Dispose(); wavePlayer = null; } if (reader != null) { reader.Dispose(); reader = null; } }
private void StartVisualization(object sender, EventArgs e) { WaveChannel32 wave = new WaveChannel32(new Mp3FileReader("test.mp3")); // WaveChannel32 wave = new WaveChannel32(new Mp3FileReader("C:\\Users\\Kapi\\Desktop\\test2.mp3")); int sampleSize = 1024; var bufferSize = 16384 * sampleSize; bufferSize = 1024; var buffer = new byte[bufferSize]; int read = 0; while (wave.Position < wave.Length) { read = wave.Read(buffer, 0, bufferSize); for (int i = 0; i < read / sampleSize; i++) { var point = BitConverter.ToSingle(buffer, i * sampleSize); _waveformPoints.Add(point); } } _waveOutDevice = new WaveOut(); _audioFileReader = new AudioFileReader("test.mp3"); //_audioFileReader = new AudioFileReader("C:\\Users\\Kapi\\Desktop\\test2.mp3"); for (int i = 0; i < _audioFileReader.TotalTime.TotalMilliseconds; i++) { _waveformPointsMiliseconds.Add(_waveformPoints[(int)((double)i / (_audioFileReader.TotalTime.TotalMilliseconds) * _waveformPoints.Count)]); } _waveOutDevice.Init(_audioFileReader); _waveOutDevice.Play(); _waveformTmr.Start(); label2.Text = _audioFileReader.TotalTime.TotalMilliseconds.ToString(); waveFormBox.Refresh(); }
private void YHnetSetup(string dst_ip, int dst_rcvport, int dst_sndport, int src_rcvport, int src_sndport) { // 初始化socket m_rcvsocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); // 绑定本地端口 IPEndPoint rcv_ep = new IPEndPoint(IPAddress.Any, src_rcvport); m_rcvsocket.Bind(rcv_ep); //m_sndsocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint snd_ep = new IPEndPoint(IPAddress.Any, src_sndport); //m_sndsocket.Bind(snd_ep); m_udpc_send = new UdpClient(snd_ep); IPEndPoint sender = new IPEndPoint(IPAddress.Parse(dst_ip), dst_rcvport); m_remote_sndep = (IPEndPoint)sender; IPEndPoint rcv = new IPEndPoint(IPAddress.Any, dst_sndport); m_remote_rcvep = (EndPoint)rcv; m_rcv_buffer = new Byte[4096]; WaveFormat wf = new WaveFormat(8000, 16, 1); m_wavePlayer = new WaveOut(); m_wave_provider = new BufferedWaveProvider(wf); m_wavePlayer.Init(m_wave_provider); m_wavePlayer.Play(); m_thread_rcv = new Thread(ThreadDoRecv); m_thread_rcv.IsBackground = true; m_thread_rcv.Start(); }
/// <summary> /// Event executed every iteration of the timer. /// </summary> private void OnTick(object sender, ElapsedEventArgs e) { // If the stream is not stopped if (State != StreamingState.Stopped) { // If there is no player and no wave device if (Player == null && WaveProvider != null) { // Create a new wave device Player = new WaveOut(); // Add a volume controller VolumeProvider = new VolumeWaveProvider16(WaveProvider); VolumeProvider.Volume = UserVolume; Player.Init(VolumeProvider); //progressBarBuffer.Maximum = (int)bufferedWaveProvider.BufferDuration.TotalMilliseconds; } // If there is a player but not a wave device else if (WaveProvider != null) { // Store the buffered seconds double BufferedSeconds = WaveProvider.BufferedDuration.TotalSeconds; // Make it stutter less by buffering up a decent amount before playing if (BufferedSeconds < 0.5 && State == StreamingState.Playing && !FullyDownloaded) { Pause(); } else if (BufferedSeconds > 4 && State == StreamingState.Buffering) { Play(); } else if (FullyDownloaded && BufferedSeconds == 0) { Stop(); // We have reached the end of the stream } } } }
private void TimerTick(object state) { if (playbackState != StreamingPlaybackState.Stopped) { if (this.waveOut == null && this.bufferedWaveProvider != null) { //Debug.WriteLine("Creating WaveOut Device"); waveOut = new WaveOut(); waveOut.PlaybackStopped += waveOut_PlaybackStopped; this.volumeProvider = new VolumeWaveProvider16(bufferedWaveProvider); this.volumeProvider.Volume = 1; waveOut.Init(volumeProvider); } else if (bufferedWaveProvider != null) { var bufferedSeconds = bufferedWaveProvider.BufferedDuration.TotalSeconds; // make it stutter less if we buffer up a decent amount before playing if (bufferedSeconds < 0.5 && this.playbackState == StreamingPlaybackState.Playing && !this.fullyDownloaded) { this.playbackState = StreamingPlaybackState.Buffering; waveOut.Pause(); //Debug.WriteLine(String.Format("Paused to buffer, waveOut.PlaybackState={0}", waveOut.PlaybackState)); } else if (bufferedSeconds > 4 && this.playbackState == StreamingPlaybackState.Buffering) { waveOut.Play(); //Debug.WriteLine(String.Format("Started playing, waveOut.PlaybackState={0}", waveOut.PlaybackState)); this.playbackState = StreamingPlaybackState.Playing; } else if (this.fullyDownloaded && bufferedSeconds == 0) { //Debug.WriteLine("Reached end of stream"); StopPlayback(); } } } }
public WaveInChannelProcessor(string streamName, string waveInSourceName, int waveInChannel, Common.ProcessRadioSignalingItemDelegate sigDelegate, Action <bool> propertyChangedAction, float initialVolume, bool recordingEnabled, Common.SignalRecordingType recordingType, int recordingKickTime, Common.NoiseFloor noiseFloor, int customNoiseFloor, bool removeNoise, bool decodeMDC1200, bool decodeGEStar, bool decodeFleetSync, bool decodeP25, string waveOutDevName) { _streamShouldPlay = true; _streamName = streamName; _waveInSourceName = waveInSourceName; _waveInChannel = waveInChannel; _sigDelegate = sigDelegate; _propertyChangedAction = propertyChangedAction; sourceActive = false; _recordingEnabled = recordingEnabled; _recordingType = recordingType; _recordingKickTime = recordingKickTime; _noiseFloor = noiseFloor; _customNoiseFloor = customNoiseFloor; _removeNoise = removeNoise; _decodeMDC1200 = decodeMDC1200; _decodeGEStar = decodeGEStar; _decodeFleetSync = decodeFleetSync; _decodeP25 = decodeP25; _waveOutDevName = waveOutDevName; bufferedWaveProvider = new BufferedWaveProvider(AudioProcessingGlobals.GetWaveFormatForChannels(1)); bufferedWaveProvider.BufferDuration = TimeSpan.FromSeconds(3); processorWaveProvider = new ProcessorWaveProvider(streamName, bufferedWaveProvider, ProcessRadioSignalingItem, propertyChangedAction, recordingEnabled, recordingType, recordingKickTime, noiseFloor, customNoiseFloor, removeNoise, decodeMDC1200, decodeGEStar, decodeFleetSync, decodeP25); volumeProvider = new VolumeWaveProvider16(processorWaveProvider); volumeProvider.Volume = initialVolume; FirePropertyChangedAction(true); WaveInManager.Instance.SetupForProcessor(this); sourceActive = true; waveOut = CreateWaveOut(); waveOut.Init(volumeProvider); waveOut.Play(); }
/// <summary> /// 语音播放器 /// </summary> /// <param name="quality"></param> /// <param name="bufferTime"></param> public AudioPlayer(int quality, int bufferTime = 50) { switch (quality) { case 1: _speexCodec = new NarrowBandSpeexCodec(); break; case 3: _speexCodec = new UltraWideBandSpeexCodec(); break; case 2: default: _speexCodec = new WideBandSpeexCodec(); break; } _waveProvider = new BufferedWaveProvider(_speexCodec.RecordFormat); _waveOut = new WaveOut(); _waveOut.Init(_waveProvider); }
private void StopPlayback() { if (playbackState != StreamingPlaybackState.Stopped) { if (!fullyDownloaded) { webRequest.Abort(); } playbackState = StreamingPlaybackState.Stopped; if (waveOut != null) { waveOut.Stop(); waveOut.Dispose(); waveOut = null; } timer1.Enabled = false; // n.b. streaming thread may not yet have exited Thread.Sleep(500); } Launcher.TFMRadioPlaying = false; }
/// <summary> /// Destroys the audio renderer. /// Makes it useless. /// </summary> private void Destroy() { lock (SyncLock) { if (AudioDevice != null) { AudioDevice.Dispose(); AudioDevice = null; } if (AudioBuffer != null) { AudioBuffer.Dispose(); AudioBuffer = null; } if (AudioProcessor != null) { AudioProcessor.Dispose(); AudioProcessor = null; } } }
private void Start(Audio.Codecs.INetworkChatCodec codec) { ShouldTryRestartOutput = false; Stop(); waveOut = GetWavePlayer(); waveProvider = new BufferedWaveProvider(codec.RecordFormat); sampleChannel = new SampleChannel(waveProvider, false); sampleStream = new NotifyingSampleProvider(sampleChannel); sampleStream.Sample += (s, e) => aggregator.Add(e.Left); waveOut.Init(sampleStream); waveOut.Play(); if (LevelManager == null) { LevelManager = new AudioLevelManagerDisconnected(); } OutputFormat = codec.RecordFormat.ToString(); }
private void CloseWaveOut() { if (playbackTimer != null) { playbackTimer.Enabled = false; playbackTimer.Dispose(); playbackTimer = null; } if (waveOut != null) { waveOut.Stop(); waveOut.Dispose(); waveOut = null; } if (waveStream != null) { waveStream.Dispose(); setVolumeDelegate = null; waveStream = null; } }
/// <summary> /// Initializes the audio renderer. /// Call the Play Method to start reading samples /// </summary> private void Initialize() { Destroy(); if (SoundTouch.IsAvailable) { AudioProcessor = new SoundTouch { Channels = Convert.ToUInt32(WaveFormat.Channels), SampleRate = Convert.ToUInt32(WaveFormat.SampleRate) }; } AudioDevice = MediaElement.RendererOptions.UseLegacyAudioOut ? new LegacyAudioPlayer(this, MediaElement.RendererOptions.LegacyAudioDevice?.DeviceId ?? -1) as IWavePlayer : new DirectSoundPlayer(this, MediaElement.RendererOptions.DirectSoundDevice?.DeviceId ?? DirectSoundPlayer.DefaultPlaybackDeviceId); SampleBlockSize = Constants.Audio.BytesPerSample * Constants.Audio.ChannelCount; var bufferLength = WaveFormat.ConvertLatencyToByteSize(AudioDevice.DesiredLatency) * MediaCore.Blocks[MediaType.Audio].Capacity / 2; AudioBuffer = new CircularBuffer(bufferLength); AudioDevice.Start(); }
public AudioPlaybackEngine(int sampleRate = 44100, int channelCount = 2) { cachedSoundFX = new Dictionary <string, CachedSound>() { { "openMenu", new CachedSound(@"res\sfx\openMenu.wav") }, { "closeMenu", new CachedSound(@"res\sfx\closeMenu.wav") }, { "openMap", new CachedSound(@"res\sfx\openMap.wav") }, { "closeMap", new CachedSound(@"res\sfx\closeMap.wav") }, { "grabBlueprint", new CachedSound(@"res\sfx\grabBlueprint.wav") } }; songTitles = new List <string>() { "Track1" }; outputDevice = new WaveOutEvent(); mixer = new MixingSampleProvider(WaveFormat.CreateIeeeFloatWaveFormat(sampleRate, channelCount)) { ReadFully = true }; outputDevice.Init(mixer); outputDevice.Play(); }
private void Start() { if (running) { return; } Debug.Assert(soundOutputDevice == null); //soundOutputDevice = new DirectSoundOut(100); soundOutputDevice = new WaveOutEvent(); ((WaveOutEvent)soundOutputDevice).NumberOfBuffers = 2; ((WaveOutEvent)soundOutputDevice).DesiredLatency = 100; //SignalGenerator gen = new SignalGenerator(44100, 1); //gen.Type = SignalGeneratorType.Square; //MixingSampleProvider mixer = new MixingSampleProvider(new[] { }); //mixer.ReadFully = true; soundOutputDevice.Init(new SampleGenerator(loadedSystem.SoundGenerator, loadedSystem.SoundGenerator.ChannelCount)); soundOutputDevice.Play(); loadedSystem.Start(); running = true; }
public Form1() { InitializeComponent(); this.MinimumSize = this.Size; if (possiblePlayers == null) { possiblePlayers = GetAllPlayers(); } #region WaveOutEvent //for (int i = 0; i < WaveOut.DeviceCount; i++) //{ // var caps = WaveOut.GetCapabilities(i); // richTextBox1.AppendText($"{caps.ProductName} \t\t {caps.ProductGuid}\n"); //} //pp = new WaveOutEvent() { DeviceNumber = 0 }; #endregion //pp = new AsioOut(AsioOut.GetDriverNames()[0]); pp = new WaveOut(); }
private bool disposedValue = false; // To detect redundant calls /// <summary> /// Dispose of the RelhaxMediaPlayer references /// </summary> /// <param name="disposing">True to dispose of managed objects</param> protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). UITimer.Dispose(); UITimer = null; waveOutDevice.Dispose(); waveOutDevice = null; audioStream.Dispose(); audioStream = null; audioFileReader2.Dispose(); audioFileReader2 = null; } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } }
protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { // Free other state (managed objects). } // Free your own state (unmanaged objects). // Set large fields to null. audioFileReader = null; waveOut = null; foreach (string file in Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\wamp")) { if (file.ToLower().EndsWith(".wav")) { File.Delete(file); } } disposed = true; } }
static Audio() { if (!initialized) { #if WINDOWS try { mixer = new WaveMixerStream32(); mixer.AutoStop = false; waveOutDevice = new DirectSoundOut(50); waveOutDevice.Init(mixer); initialized = true; } catch (Exception driverCreateException) { Console.WriteLine(String.Format("{0}", driverCreateException.Message)); return; } #endif } }
public void CloseWaveOut() { try { if (waveOutDevice != null) { waveOutDevice.Stop(); playbackState = CustomPlayBackState.Stopped; } if (sampleProvider != null) { sampleProvider.Dispose(); sampleProvider = null; audioFileReader = null; } if (waveOutDevice != null) { waveOutDevice.Dispose(); waveOutDevice = null; } } catch { } }
private void UnloadAudio() { if (waveOutDevice != null) { waveOutDevice.Stop(); } if (mainOutputStream != null) { // this one really closes the file and ACM conversion volumeStream.Close(); volumeStream = null; // this one does the metering stream mainOutputStream.Close(); mainOutputStream = null; } if (waveOutDevice != null) { waveOutDevice.Dispose(); waveOutDevice = null; } }
/// <summary> /// Creates Live audio player. /// </summary> /// <param name="provider">Specified audio provider.</param> /// <param name="preBuffer">Audioprebuffer in milli seconds</param> /// <param name="fftAnalysis">Determines wheather FFT analyzer is enabled or not.</param> public LiveAudioPlayer(IAudioProvider provider, float preBuffer = 0.3F, bool fftAnalysis = false)//default 0.3F as 300 ms { _provider = provider; _preBufferLength = preBuffer; _format = new WaveFormat(provider.SamplingRate(), provider.Bits(), provider.ChannelCount()); // must match the waveformat of the raw audio _waveOut = new WaveOut(); //new DirectSoundOut(); //new WaveOut(); _buffer = new BufferedWaveProvider(_format); _buffer.DiscardOnBufferOverflow = true; if (fftAnalysis) { InitializeAggregator(); _waveOut.Init(_aggregator); } else { _waveOut.Init(_buffer); } _byteRate = (provider.Bits() / 8) * provider.ChannelCount() * provider.SamplingRate(); _provider.DataChunkRecieved += AudioChunkRecieved; }
public void PlaySong() { if (playlist.Count < 1) { return; } if (player != null && player.PlaybackState != PlaybackState.Stopped) { player.Stop(); } if (player != null) { player.Dispose(); player = null; } player = new WaveOutEvent(); var audioFilePath = playlist.First(); var fileWaveStream = new AudioFileReader(audioFilePath); player.Init(fileWaveStream); player.Play(); player.PlaybackStopped += (sender, evn) => { PlaySong(); }; }
public void BrowseFile(bool soft = false) // and load { if (wavePlayer != null) { wavePlayer.Dispose(); wavePlayer = null; } if (HasFile && soft) { } else { if (ofd.ShowDialog() != DialogResult.OK) { return; } } IsUrlMedia = false; LoadedFile = ofd.FileNames; Load(); // waiting for play button to be depressed }
public void Update() { if (playbackState != StreamingPlaybackState.Stopped) { if (waveOut == null && bufferedWaveProvider != null) { waveOut = CreateWaveOut(); waveOut.PlaybackStopped += OnPlaybackStopped; volumeProvider = new VolumeWaveProvider16(bufferedWaveProvider); volumeProvider.Volume = Volume; waveOut.Init(volumeProvider); } else if (bufferedWaveProvider != null) { volumeProvider.Volume = Volume; var bufferedSeconds = bufferedWaveProvider.BufferedDuration.TotalSeconds; // make it stutter less if we buffer up a decent amount before playing if (bufferedSeconds < 0.5 && playbackState == StreamingPlaybackState.Playing && !fullyDownloaded) { Pause(); } else if (bufferedSeconds > 4 && playbackState == StreamingPlaybackState.Buffering) { Play(); } else if (fullyDownloaded && bufferedSeconds == 0) { StopPlayback(); } } } else { this.StreamTitle = ""; } }
private void timer1_Tick(object sender, EventArgs e) { if (playbackState != StreamingPlaybackState.Stopped) { if (waveOut == null && bufferedWaveProvider != null) { Debug.WriteLine("Creating WaveOut Device"); waveOut = CreateWaveOut(); waveOut.PlaybackStopped += OnPlaybackStopped; volumeProvider = new VolumeWaveProvider16(bufferedWaveProvider); //volumeProvider.Volume = volumeSlider1.Volume; waveOut.Init(volumeProvider); progressBarBuffer.Maximum = (int)bufferedWaveProvider.BufferDuration.TotalMilliseconds; } else if (bufferedWaveProvider != null) { var bufferedSeconds = bufferedWaveProvider.BufferedDuration.TotalSeconds; ShowBufferState(bufferedSeconds); // make it stutter less if we buffer up a decent amount before playing if (bufferedSeconds < 0.5 && playbackState == StreamingPlaybackState.Playing && !fullyDownloaded) { Pause(); autonextsong(); } else if (bufferedSeconds > 4 && playbackState == StreamingPlaybackState.Buffering) { Play(); } else if (fullyDownloaded && bufferedSeconds == 0) { Debug.WriteLine("Reached end of stream"); StopPlayback(); autonextsong(); } } } }
private void PlayMusicFile(PlaylistItem fileInfo) { if (wavePlayer == null) { wavePlayer = new WaveOutEvent(); audioFile = new AudioFileReader(fileInfo.filePath); audioFile.Volume = localVolume; LS = new LoopStream(audioFile, enableLooping); if (LS == null) { return; } if (LS.EnableLooping) { wavePlayer.Init(LS); } else { wavePlayer.Init(audioFile); } wavePlayer.PlaybackStopped += OnPlaybackStopped; wavePlayer.Play(); currentItem = fileInfo; } else { wavePlayer.Stop(); wavePlayer.Dispose(); wavePlayer = null; } }
private void Timer_Tick(object state) { lock (_playLock) { if (playbackState != StreamingPlaybackState.Stopped) { if (waveOut == null && bufferedWaveProvider != null) { Console.WriteLine("Creating WaveOut Device"); waveOut = new WaveOut(); waveOut.PlaybackStopped += OnPlaybackStopped; volumeProvider = new VolumeWaveProvider16(bufferedWaveProvider); //volumeProvider.Volume = volumeSlider1.Volume; volumeProvider.Volume = 1; waveOut.Init(volumeProvider); } else if (bufferedWaveProvider != null) { var bufferedSeconds = bufferedWaveProvider.BufferedDuration.TotalSeconds; // 如果我们在比赛前缓冲了一个适当的数量,就可以减少口吃 if (bufferedSeconds < 0.5 && playbackState == StreamingPlaybackState.Playing && !fullyDownloaded) { Buffering(); } else if (bufferedSeconds > 4 && playbackState == StreamingPlaybackState.Buffering) { Play(); } else if (fullyDownloaded) { Console.WriteLine("Reached end of stream"); StopPlayback(); } } } } }
/// <summary> /// The Play function starts playback of the drum machine. /// </summary> private void Play(int patternNum, bool master) { // 16 / (tempo / 60) int wait = (16 / (this.tempo / 60)) * 1000; System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer(); timer.Interval = wait; timer.Tick += (sender, e) => timer_Elapsed(sender, e, patternNum); if (master == true) { if (waveOut != null) { waveOut.Dispose(); waveOut = null; } waveOut = new WaveOut(); this.patternSequencer.Reset(patternList[patternNum]); this.patternSequencer.Tempo = tempo; waveOut.Init(patternSequencer); waveOut.Play(); timer.Start(); } else { if (waveOut != null) { Stop(); } waveOut = new WaveOut(); this.patternSequencer.Reset(patternList[patternNum]); this.patternSequencer.Tempo = tempo; waveOut.Init(patternSequencer); waveOut.Play(); } }
public void StopWavePlayer() { try { if (wavePlayer != null) { if (wavePlayer.PlaybackState == PlaybackState.Playing) { wavePlayer.Stop(); } wavePlayer.Dispose(); wavePlayer = null; } if (volumeSampleProvider != null) { volumeSampleProvider = null; } if (reader != null) { reader.Dispose(); reader.Close(); reader = null; } } catch (Exception ex) { wavePlayer = null; volumeSampleProvider = null; reader = null; string sMsg = ex.Message.ToString(); } }
public void Load(string filename) { if (player != null) { player.Stop(); player.Dispose(); } if (reader != null) { reader.Dispose(); reader.Unload(); } reader = new GmeReader(filename); volumeSampleProvider = new VolumeSampleProvider(reader.ToSampleProvider()); var waveOut = new DirectSoundOut(); waveOut.Init(volumeSampleProvider); player = waveOut; }
/** * Constructor, initializes the audio system for * 44100Hz 32-bit float stereo output. */ public AudioDevice() { // BufferedWaveProvider bufferedWaveProvider = new BufferedWaveProvider(WaveFormat.CreateIeeeFloatWaveFormat(44100, 2)); bufferedWaveProvider.BufferDuration = TimeSpan.FromMinutes(10); bufferedWaveProvider.DiscardOnBufferOverflow = true; // waveOut /* * This is the default and recommended approach if you are creating a WaveOut object * from the GUI thread of a Windows Forms or WPF application. * Whenever WaveOut wants more data it posts a message that is handled by the * Windows message pump of an invisible new window. * You get this callback model by default when you call the empty WaveOut constructor. * However, it will not work on a background thread, since there is no message pump. * */ waveOut = new WaveOut(WaveCallbackInfo.FunctionCallback()); // seems to be the best way //waveOut = new WaveOut(); //waveOut.Volume = 0.5f; waveOut.Init(bufferedWaveProvider); waveOut.PlaybackStopped += new EventHandler <StoppedEventArgs>(_waveOutDevice_PlaybackStopped); waveOut.Play(); }