Esempio n. 1
0
 private void Play()
 {
     if (File.Exists(localPath))
     {
         SetState("Playing...");
         player.OpenFile(localPath, TStreamFormat.sfAutodetect);
         player.StartPlayback();
     }
     else
     {
         Log.Write("Unable to play {0}, local file does not exist?", localPath);
         SetState("Error!");
     }
 }
Esempio n. 2
0
        static void Main(string[] args)
        {
            ZPlay play = new ZPlay();

            play.OpenFile(@"E:\kugou【数码宝贝】Butterfly-乐队Cover+被选中的八个女子.mp3", TStreamFormat.sfAutodetect);
            play.StartPlayback();
        }
Esempio n. 3
0
        public static void LibZPL(string FileInGameData)
        {
            ZPlay player = new ZPlay();

            // Private player As ZPlay
            player = new ZPlay();
            player.OpenFile(FileInGameData, TStreamFormat.sfOgg);
            player.StartPlayback();
        }
Esempio n. 4
0
        private void CheckMailbox(object sender, EventArgs args)
        {
            string incomingMessagesTranslationMode = incomingLangComboBox.Text;

            try
            {
                var result = _flowClientWorker.GetMessage(incomingMessagesTranslationMode);

                if (result.Success)
                {
                    if (incomingMessagesRichTextBox.InvokeRequired)
                    {
                        incomingMessagesRichTextBox.Invoke((MethodInvoker)(() =>
                        {
                            incomingMessagesRichTextBox.AppendText(
                                Environment.NewLine + new string('-', 168) +
                                Environment.NewLine +
                                $"From {result.SenderName} [{result.SenderId}] : {result.MessageBody}");
                        }));
                    }
                    else
                    {
                        incomingMessagesRichTextBox.AppendText(
                            Environment.NewLine + new string('-', 168) +
                            Environment.NewLine +
                            $"From {result.SenderName} [{result.SenderId}] : {result.MessageBody}");
                    }

                    try
                    {
                        ZPlay player = new ZPlay();

                        if (player.OpenFile(@"Resources/OwOw.mp3", TStreamFormat.sfAutodetect))
                        {
                            player.SetMasterVolume(100, 100);
                            player.SetPlayerVolume(100, 100);

                            player.StartPlayback();
                        }
                    }
                    catch (Exception)
                    {
                        // I don't care if soundplayer is going crazy
                    }
                }
            }
            catch (Exception exception)
            {
                Debug.WriteLine(exception);
                MessageBox.Show(string.IsNullOrWhiteSpace(exception.Message)
                    ? "Something is wrong: check your server connection"
                    : exception.Message);
            }
        }
Esempio n. 5
0
        static void Main(string[] args)
        {
            Console.WriteLine("Playing test.mp3. Press Q to quit.\n");
            // create ZPlay class
            ZPlay player = new ZPlay();

            // open file
            if (player.AddFile("1.mp3", TStreamFormat.sfAutodetect) == false)
            {
                Console.WriteLine(player.GetError());
                return;
            }


            // get song length
            TStreamInfo info = new TStreamInfo();

            player.GetStreamInfo(ref info);
            Console.WriteLine("Length: {0:G}:{1:G}:{2:G}:{3:G}",
                              info.Length.hms.hour,
                              info.Length.hms.minute,
                              info.Length.hms.second,
                              info.Length.hms.millisecond);

            // start playing
            player.StartPlayback();

            TStreamStatus status = new TStreamStatus();
            TStreamTime   time   = new TStreamTime();

            status.fPlay = true;

            while (status.fPlay)
            {
                player.GetPosition(ref time);
                Console.Write("Pos: {0:G}:{1:G}:{2:G}:{3:G}\r",
                              time.hms.hour,
                              time.hms.minute,
                              time.hms.second,
                              time.hms.millisecond);
                player.GetStatus(ref status);
                System.Threading.Thread.Sleep(50);
                if (Console.KeyAvailable)
                {
                    var cki = Console.ReadKey(true);
                    if (cki.Key == ConsoleKey.Q)
                    {
                        player.StopPlayback();
                    }
                }
            }
        }
Esempio n. 6
0
        void PlayNews()
        {
            String _newsurl = "http://public.npr.org/anon.npr-podcasts/podcast/500005/376418824/npr_376418824.mp3?dl=1";


            WebClient Client = new WebClient();

            Client.DownloadFile(_newsurl, "nprnews.mp3");

            //System.Diagnostics.ProcessStartInfo thePSI = new System.Diagnostics.ProcessStartInfo("wmplayer");
            //thePSI.Arguments = _newsurl;
            //thePSI.CreateNoWindow = true;
            //thePSI.UseShellExecute = true;
            //System.Diagnostics.Process.Start(thePSI);


            #endregion

            #region "MP3Player"
            ZPlay player = new ZPlay();
            if (player.OpenFile("nprnews.mp3", TStreamFormat.sfAutodetect) == false)
            {
                // error
                System.Windows.Forms.MessageBox.Show("can't do it");

                //Windows 8.1 Way
                //var dialog = new MessageDialog("Are you sure?");
                //dialog.Title = "Really?";
                //dialog.Commands.Add(new UICommand { Label = "Ok", Id = 0 });
                //dialog.Commands.Add(new UICommand { Label = "Cancel", Id = 1 });
                //var res = await dialog.ShowAsync();
            }
            //TODO announce how long the file is
            //TODO convert to direct stream of the mp3 file from the source, needs to create a memory
            //stream in order to stream file.  LoadDynamicInfo and StreamLength should be possible
            else
            {
                player.StartPlayback();
            }
        }
Esempio n. 7
0
        public void StartLibZPlay()
        {
            _stopPlayer = false;

            // open file
            var fileName =
                "wavein://src=microphone;volume=50;";
            // @"C:\Users\david_000\Music\my best remixes\10 vibromatic.mp3";

            FixedSizedQueue <FFTData> fftDatas = new FixedSizedQueue <FFTData>();

            fftDatas.Limit = 5000;

            if (!_player.OpenFile(fileName, TStreamFormat.sfAutodetect))
            {
                return;
            }
            _player.StartPlayback();
            Pause();
            while (_continue && !_stopPlayer)
            {
                FFTData fftData = new FFTData();
                _player.GetFFTData(512, TFFTWindow.fwRectangular, ref fftData.HarmonicNumber, ref fftData.HarmonicFreq, ref fftData.LeftAmplitude, ref fftData.RightAmplitude, ref fftData.LeftPhase, ref fftData.RightPhase);
                fftDatas.Enqueue(fftData);
                if (change(fftDatas))
                {
                    _display = true;
                }

                System.Threading.Thread.Sleep(1);
            }

            _player.Close();

            if (_continue)
            {
                StartLibZPlay();
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Gets called on average every 500ms. This is a console application, so no SynchronizationContext
        /// available. This means this function is called on theNetConnection thread
        /// watch out for that.!
        /// </summary>
        private void NC_OnTick(object sender)
        {
            // feed zplay with data received from netstream
            // Minimum buffer voordat we starten met afspelen
            TStreamStatus status = new TStreamStatus();

            zPlay.GetStatus(ref status);

            // Not playing and buffer has enough data to examine mp3 to start playing
            if (!status.fPlay && zPlayBuffer.UsedBytes >= 8192)
            {
                byte[] tmpBuffer = new byte[8192];
                zPlayBuffer.Read(tmpBuffer, 8192);

                if (!(zPlay.OpenStream(true, true, ref tmpBuffer, 8192, TStreamFormat.sfMp3)))
                {
                    // Got an error with libzplay
                    Console.WriteLine(zPlay.GetError());
                    return;
                }
                // Start playing audio
                zPlay.StartPlayback();
            }
            else if (status.fPlay && zPlayBuffer.UsedBytes > 0)
            {
                int    bufRead   = Convert.ToInt32(zPlayBuffer.UsedBytes);
                byte[] tmpBuffer = new byte[bufRead];
                zPlayBuffer.Read(tmpBuffer, bufRead);

                // Push data into libzplay so it can continue playing audio
                if (!zPlay.PushDataToStream(ref tmpBuffer, Convert.ToUInt32(bufRead)))
                {
                    // Got an error with libzplay
                    Console.WriteLine(zPlay.GetError());
                    return;
                }
            }
        }
Esempio n. 9
0
 /// <summary>
 /// 试听,会传入一个文件路径
 /// </summary>
 /// <param name="path"></param>
 public void Play(string path)
 {
     try
     {
         if (!File.Exists(path))
         {
             MessageBox.Show(string.Format("音频文件{0}不存在!", path));
             return;
         }
         m_bIsCurrentFromWarningInfo = false;
         if (m_currentPlayer.OpenFile(path, TStreamFormat.sfAutodetect))
         {
             m_currentPlayer.StartPlayback();
         }
     }
     catch (Exception exp)
     {
         System.Diagnostics.Debug.WriteLine(exp.Message);
     }
     finally
     {
     }
 }
Esempio n. 10
0
		private void OpenFileDialog1_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
		{

			
            
			TStreamFormat format = player.GetFileFormat(OpenFileDialog1.FileName);
   
			if (LoadMode == 0)
			{
                player.Close();
				if (! (player.OpenFile(OpenFileDialog1.FileName, TStreamFormat.sfAutodetect )))
				{
					MessageBox.Show(player.GetError(), string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
				}
			}
			else if (LoadMode == 1)
			{
                player.Close();
				System.IO.FileInfo fInfo = new System.IO.FileInfo(OpenFileDialog1.FileName);
				long numBytes = fInfo.Length;
				System.IO.FileStream fStream = new System.IO.FileStream(OpenFileDialog1.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
				System.IO.BinaryReader br = new System.IO.BinaryReader(fStream);
				byte[] stream_data = null;

				stream_data = br.ReadBytes(System.Convert.ToInt32((int)(numBytes)));
                if (!(player.OpenStream(true, false, ref stream_data, System.Convert.ToUInt32(numBytes), format)))
				{
					MessageBox.Show(player.GetError(), string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}

				br.Close();
				fStream.Close();
			}
			else if (LoadMode == 2)
			{
                player.Close();
				BufferCounter = 0;

				System.IO.FileInfo fInfo = new System.IO.FileInfo(OpenFileDialog1.FileName);
				uint numBytes = System.Convert.ToUInt32(fInfo.Length);
				if (br != null)
				{
					br.Close();
				}
				if (fStream != null)
				{
					fStream.Close();
				}

				br = null;
				fStream = null;

				fStream = new System.IO.FileStream(OpenFileDialog1.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
				br = new System.IO.BinaryReader(fStream);
				byte[] stream_data = null;
				uint small_chunk = 0;
				small_chunk = System.Convert.ToUInt32(Math.Min(100000, numBytes));
				// read small chunk of data
				stream_data = br.ReadBytes(System.Convert.ToInt32((int)(small_chunk)));
				// open stream
				if (! (player.OpenStream(true, true, ref stream_data, System.Convert.ToUInt32(stream_data.Length), format)))
				{
					MessageBox.Show(player.GetError(), string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}

				// read more data and push into stream
				stream_data = br.ReadBytes(System.Convert.ToInt32((int)(small_chunk)));
				player.PushDataToStream(ref stream_data, System.Convert.ToUInt32(stream_data.Length));
			}
            else if (LoadMode == 3)
            {
                if (!(player.AddFile(OpenFileDialog1.FileName, TStreamFormat.sfAutodetect)))
                {
                    MessageBox.Show(player.GetError(), string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }


            }

			showinfo();
            player.StartPlayback();

		}
Esempio n. 11
0
		private void Form1_Load(object sender, System.EventArgs e)
		{
			player = new ZPlay();
			ReverseMode = false;
			Echo = false;

			int left = 0;
			int right = 0;
			player.GetMasterVolume(ref left, ref right);
			leftmastervolume.Value = 100 - left;
			rightmastervolume.Value = 100 - right;
			player.GetPlayerVolume(ref left, ref right);
			leftplayervolume.Value = 100 - left;
			rightplayervolume.Value = 100 - right;

			// callback
			CallbackFunc = new TCallbackFunc(MyCallbackFunc);
            player.SetCallbackFunc(CallbackFunc, (TCallbackMessage)((TCallbackMessage.MsgEnterVolumeSlideAsync | TCallbackMessage.MsgExitVolumeSlideAsync | TCallbackMessage.MsgStreamBufferDoneAsync | TCallbackMessage.MsgNextSongAsync )), 0);

         
			// echo

            
			TEchoEffect[] effect = new TEchoEffect[2];

			effect[0].nLeftDelay = 500;
			effect[0].nLeftSrcVolume = 50;
			effect[0].nLeftEchoVolume = 30;
			effect[0].nRightDelay = 500;
			effect[0].nRightSrcVolume = 50;
			effect[0].nRightEchoVolume = 30;

			effect[1].nLeftDelay = 30;
			effect[1].nLeftSrcVolume = 50;
			effect[1].nLeftEchoVolume = 30;
			effect[1].nRightDelay = 30;
			effect[1].nRightSrcVolume = 50;
			effect[1].nRightEchoVolume = 30;

            player.SetEchoParam(ref effect, 2);
  
            
            /*
            TEchoEffect[] test1 = new TEchoEffect[2];
            int n = player.GetEchoParam(ref test1);
            int i;
            for (i = 0; i < n; i++)
            {
                MessageBox.Show(test1[i].nLeftDelay.ToString());
            }
            */

            /*
            int[] EqPoints = new int[9] { 100, 200, 300, 1000, 2000, 3000, 5000, 7000, 12000 };
            player.SetEqualizerPoints(ref EqPoints, 9);
            */

            /*
            int[] testeq = new int[1];
            int num = player.GetEqualizerPoints(ref testeq);
            int i1;
            for (i1 = 0; i1 < num; i1++)
            {
                MessageBox.Show(testeq[i1].ToString ());

            }
             */
            

            /*
            TWaveOutInfo WaveOutInfo = new TWaveOutInfo();
            int WaveOutNum = player.EnumerateWaveOut();
            uint i;
            for (i = 0; i < WaveOutNum; i++)
            {
                if (player.GetWaveOutInfo(i, ref WaveOutInfo))
                {
                    MessageBox.Show(WaveOutInfo.ProductName );

                }
            }
            
            */


			ComboBox1.SelectedIndex = 0;
			ComboBox2.SelectedIndex = 7;
			ComboBox3.SelectedIndex = 11;

            ComboBox4.SelectedIndex = 0;
            ComboBox5.SelectedIndex = 0;

			if (My.MyApplication.Application.CommandLineArgs.Count != 0)
			{

				player.Close();

				if (LoadMode == 0)
				{
                    if (!(player.OpenFile(My.MyApplication.Application.CommandLineArgs[0], TStreamFormat.sfAutodetect)))
					{
						MessageBox.Show(player.GetError(), string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Error);
					}
				}

				showinfo();
                player.StartPlayback();
			}

		}
Esempio n. 12
0
 void ChkWavesDoubleClick(object sender, EventArgs e)
 {
     gPlayer.StopPlayback();
     gPlayer.StartPlayback();
     textBox1.Focus();
 }
Esempio n. 13
0
 public void PlayMusicFromURL(AudioFile audio)
 {
     player2.OpenFile(audio.Url, TStreamFormat.sfAutodetect);
     player2.StartPlayback();
 }
Esempio n. 14
0
        private void RegisterControlsEvents()
        {
            #region Menu Buttons

            loadAudioFileButtonAdv.Click += (sender, args) => OpenAudioFile(ref Player);

            //secondLoadAudioFileButtonAdv.Click +=
            //    (sender, args) =>
            //    {
            //        OpenAudioFile(secondAxWindowsMediaPlayer, ref _secondAudioFilePath);
            //        this.Height = 600;
            //        secondAxWindowsMediaPlayer.Location = new Point(
            //            firstAxWindowsMediaPlayer.Left,
            //            secondAxWindowsMediaPlayer.Top
            //        );
            //    };

            #endregion

            pitchTrackBarEx.MouseUp += (sender, args) =>
            {
                int pitchValue = ((TrackBarEx)sender).Value;
                pitchNumericUpDown.Value = pitchValue >= 10 ? pitchValue : 10;
            };

            pitchNumericUpDown.ValueChanged += (sender, args) =>
            {
                int pitchValue = (int)((NumericUpDown)sender).Value;
                pitchTrackBarEx.Value = pitchValue;

                Player?.SetPitch(pitchValue);
            };


            // freeeeeeeeeeeee

            frequencyTrackBarEx.MouseUp += (sender, args) =>
            {
                int pitchValue = ((TrackBarEx)sender).Value;
                frequencyNumericUpDown.Value = pitchValue >= 20 ? pitchValue : 20;
            };

            frequencyNumericUpDown.ValueChanged += (sender, args) =>
            {
                int pitchValue = (int)((NumericUpDown)sender).Value;
                frequencyTrackBarEx.Value = pitchValue;

                _metronomePlayer?.SetPitch(pitchValue);
            };

            // periooooooooooooooo

            periodicityTrackBarEx.MouseUp += (sender, args) =>
            {
                int tempoValue = ((TrackBarEx)sender).Value;
                //periodicityTextBox.Text = $@"{BpmToPeriodicity(tempoValue >= 20 ? tempoValue : 20)}";
                periodicityTextBox.Text =
                    $@"{BpmToPeriodicity(periodicityTrackBarEx.Maximum - tempoValue + periodicityTrackBarEx.Minimum)}";
            };

            periodicityTextBox.TextChanged += (sender, args) =>
            {
                decimal periodicityValue = decimal.Parse(periodicityTextBox.Text);
                periodicityTrackBarEx.Value = periodicityTrackBarEx.Maximum - PeriodicityToBPM(periodicityValue) +
                                              periodicityTrackBarEx.Minimum;

                _metronomePlayer?.SetTempo(periodicityTrackBarEx.Maximum - periodicityTrackBarEx.Value +
                                           periodicityTrackBarEx.Minimum);
            };


            //rateTrackBarEx.Click += (sender, args) =>
            //{
            //    int rateValue = ((TrackBarEx)sender).Value;
            //    Player?.SetTempo(rateValue);
            //};

            tempoTrackBarEx.MouseUp += (sender, args) =>
            {
                int tempoValue = ((TrackBarEx)sender).Value;
                tempoNumericUpDown.Value = tempoValue >= 10 ? tempoValue : 10;
            };

            tempoNumericUpDown.ValueChanged += (sender, args) =>
            {
                int tempoValue = (int)((NumericUpDown)sender).Value;
                tempoTrackBarEx.Value = tempoValue;

                Player?.SetTempo(tempoValue);
            };

            reversePlaybackToggleButton.ToggleStateChanged += (sender, args) =>
            {
                if (Player == null)
                {
                    return;
                }

                ToggleButton self = (ToggleButton)sender;

                if (self.ToggleState == ToggleButtonState.Active)
                {
                    Player?.ReverseMode(true);
                }
                else
                {
                    // ToggleButtonState.Inactive
                    Player?.ReverseMode(false);
                }
            };

            playbackProgressBarAdv.MouseDown += (sender, args) =>
            {
                //if (args.Button != MouseButtons.Left)
                //    return;

                TStreamTime newPosition = new TStreamTime();
                TStreamInfo info        = GetStreamInfo(ref Player);

                newPosition.ms = Convert.ToUInt32(
                    args.X * info.Length.ms / Convert.ToDouble(((ProgressBarAdv)sender).Size.Width));


                Player?.Seek(TTimeFormat.tfMillisecond, ref newPosition, TSeekMethod.smFromBeginning);
            };

            _volumeRadialMenuSlider.SliderValueChanged += (sender, args) =>
            {
                int volumeLevel = (int)((RadialMenuSlider)sender).SliderValue;

                if (FFTPictureBox.InvokeRequired)
                {
                    FFTPictureBox.Invoke((MethodInvoker)(() => { Player?.SetPlayerVolume(volumeLevel, volumeLevel); }));
                }
                else
                {
                    Player?.SetPlayerVolume(volumeLevel, volumeLevel);
                }
            };

            volumePictureBox.Click += (sender, args) =>
            {
                _radialMenu = new RadialMenu();

                #region Volume Radial Menu Slider

                _volumeRadialMenuSlider.MinimumValue = 0;
                _volumeRadialMenuSlider.MaximumValue = 100;
                _volumeRadialMenuSlider.SliderValue  = 50;
                _volumeRadialMenuSlider.Text         = "VOLUME";

                #endregion

                #region Radial Menu Properties Settings

                _radialMenu.WedgeCount = 1;

                _radialMenu.MenuIcon =
                    Image.FromFile($@"{Path.GetDirectoryName(Application.ExecutablePath)}\Icons\Volume-high-icon.png");

                _radialMenu.MenuVisibility       = true;
                _radialMenu.PersistPreviousState = true;
                _radialMenu.UseIndexBasedOrder   = true;

                _radialMenu.RadialMenuSliderDrillDown(_volumeRadialMenuSlider);

                #region TRASH

                //_radialMenu.Items.Add(_volumeRadialMenuSlider);
                //_radialMenu.Icon = Image
                //    .FromFile($@"{Path.GetDirectoryName(Application.ExecutablePath)}\Icons\arrow-back-icon.png");


                //ImageCollection ic = new ImageCollection();
                //ic.Add(Image.FromFile($@"{Path.GetDirectoryName(Application.ExecutablePath)}\Icons\arrow-back-icon.png"));

                //_radialMenu.ImageCollection = ic;

                //_radialMenu.DisplayStyle = DisplayStyle.TextAboveImage;
                //ImageList imageList = new ImageList();
                //string[] files = Directory.GetFiles($@"{Path.GetDirectoryName(Application.ExecutablePath)}\Icons");

                //foreach (string file in files)
                //{
                //    imageList.Images.Add("volume", Image.FromFile(file));
                //}

                //_radialMenu.ImageList = ImageListAdv.FromImageList(imageList);

                #endregion

                #endregion

                #region Show Radial Menu

                this.Controls.Add(_radialMenu);
                _radialMenu.ShowRadialMenu();
                //_radialMenu.HidePopup();
                //_radialMenu.ShowPopup(new Point());

                #endregion

                _radialMenu.PreviousLevelOpened += (radialMenuSender, opening) => _radialMenu.Dispose();

                // Emulate mouse click on 50% Volume on _volumeRadialMenuSlider
                // because there's a library bug that cannot update value
                // by .SliderValue property as it's meant to be updated.
                Point location = MousePosition;
                LeftMouseClick(location.X - 40, location.Y + 15);
            };


            FFTPictureBox.Paint += (sender, args) =>
            {
                IntPtr MyDeviceContext = default(IntPtr);
                MyDeviceContext = args.Graphics.GetHdc();
                Player?.DrawFFTGraphOnHDC(MyDeviceContext, 0, 0, FFTPictureBox.Width, FFTPictureBox.Height);
                args.Graphics.ReleaseHdc(MyDeviceContext);
            };

            playToggleButton.ToggleStateChanged += (sender, args) =>
            {
                if (Player == null)
                {
                    return;
                }

                if (playToggleButton.ToggleState == ToggleButtonState.Active)
                {
                    Player.StartPlayback();
                    //_timer.Start();
                    return;
                }
                else
                {
                    Player.StopPlayback(); // ToggleButtonState.Inactive
                    //_timer.Stop();
                }
            };

            metronomeToggleButton.ToggleStateChanged += (sender, args) =>
            {
                if (metronomeToggleButton.ToggleState == ToggleButtonState.Active)
                {
                    if (_metronomePlayer == null)
                    {
                        _metronomePlayer = new ZPlay();
                    }

                    if (_metronomePlayer.OpenFile(@"Resources\metronom.mp3", TStreamFormat.sfAutodetect) == false)
                    {
                        MessageBox.Show($@"ERROR {_metronomePlayer.GetError()}");
                        return;
                    }

                    _metronomePlayer.StartPlayback();

                    _metronomePlayer.SetMasterVolume(100, 100);
                    _metronomePlayer.SetPlayerVolume(100, 100);

                    _isMetronomeSwitch = true;
                }
                else
                {
                    _metronomePlayer.StopPlayback(); // ToggleButtonState.Inactive
                    _isMetronomeSwitch = false;
                }
            };

            playerVolumeTrackBarEx.Scroll += (sender, args) =>
            {
                int volumeLevel = ((TrackBarEx)sender).Value;
                Player?.SetPlayerVolume(volumeLevel, volumeLevel);
            };

            masterVolumeTrackBarEx.Scroll += (sender, args) =>
            {
                int volumeLevel = ((TrackBarEx)sender).Value;
                Player?.SetMasterVolume(volumeLevel, volumeLevel);
            };

            this.MouseDown += (sender, mouseEventArgs) =>
            {
                if (mouseEventArgs.Button == MouseButtons.Left)
                {
                    ReleaseCapture();
                    SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
                }
            };

            closePictureBox.Click += (sender, args) => this.Close();

            #region _secondForm Control Buttons

            ReplayPictureBox.Click      += OnReplayPictureBoxOnClick;
            PlayResumePictureBox.Click  += OnPlayResumePictureBoxOnClick;
            PausePictureBox.Click       += OnPausePictureBoxOnClick;
            StopPictureBox.Click        += OnStopPictureBoxOnClick;
            RewindPictureBox.Click      += OnRewindPictureBoxOnClick;
            FastForwardPictureBox.Click += OnFastForwardPictureBoxOnClick;

            #endregion
        }
Esempio n. 15
0
        private void RegisterEventHandlers()
        {
            authButton.Click += (sender, args) =>
            {
                Task.Run(() =>
                {
                    try
                    {
                        bool authenticated = _flowClientWorker.Authenticate(
                            login: authLoginTextBox.Text,
                            password: authPassTextBox.Text);

                        MessageBox.Show($@"Authenticated: {authenticated}");
                    }
                    catch (Exception exception)
                    {
                        Debug.WriteLine(exception);
                        MessageBox.Show(string.IsNullOrWhiteSpace(exception.Message)
                            ? "Something is wrong: check your server connection"
                            : exception.Message);
                    }
                });
            };

            connectToServerButton.Click += (sender, args) =>
            {
                Task.Run(() =>
                {
                    try
                    {
                        bool connected = _flowClientWorker.Connect(
                            ipAddress: IPAddress.Parse(serverIpAddressTextBox.Text.Trim()),
                            port: int.Parse(serverPortTextBox.Text.Trim()));

                        MessageBox.Show($@"Connected: {connected}");
                    }
                    catch (Exception exception)
                    {
                        Debug.WriteLine(exception);
                        MessageBox.Show(string.IsNullOrWhiteSpace(exception.Message)
                            ? "Something is wrong: check your server connection"
                            : exception.Message);
                    }
                });
            };

            registerButton.Click += (sender, args) =>
            {
                Task.Run(() =>
                {
                    try
                    {
                        bool registered = _flowClientWorker.Register(
                            login: registerLoginTextBox.Text,
                            password: registerPassTextBox.Text,
                            name: registerNameTextBox.Text);

                        MessageBox.Show(registered
                            ? @"Registered successfully"
                            : @"Registration failed");
                    }
                    catch (Exception exception)
                    {
                        Debug.WriteLine(exception);
                        MessageBox.Show(string.IsNullOrWhiteSpace(exception.Message)
                            ? "Something is wrong: check your server connection"
                            : exception.Message);
                    }
                });
            };

            translateButton.Click += (sender, args) =>
            {
                Task.Run(() =>
                {
                    if (string.IsNullOrWhiteSpace(translateInputRichTextBox.Text))
                    {
                        return;
                    }
                    try
                    {
                        string inputTextLang  = fromLangComboBox.Text;
                        string outputTextLang = toLangComboBox.Text;

                        string translatedText = _flowClientWorker.Translate(
                            sourceText: translateInputRichTextBox.Text,
                            sourceTextLang: inputTextLang,
                            targetTextLanguage: outputTextLang);

                        if (translateOutputRichTextBox.InvokeRequired)
                        {
                            translateOutputRichTextBox.Invoke((MethodInvoker)(() =>
                            {
                                translateOutputRichTextBox.Text = translatedText;
                            }));
                        }
                        else
                        {
                            translateOutputRichTextBox.Text = translatedText;
                        }
                    }
                    catch (Exception exception)
                    {
                        Debug.WriteLine(exception);
                        MessageBox.Show(string.IsNullOrWhiteSpace(exception.Message)
                            ? "Something is wrong: check your server connection"
                            : exception.Message);
                    }
                });
            };

            sendMessageButton.Click += (sender, args) =>
            {
                Task.Run(() =>
                {
                    if (string.IsNullOrWhiteSpace(outgoingMessagesRichTextBox.Text))
                    {
                        return;
                    }

                    string recipient          = recipientTextBox.Text.Trim();
                    string messageBody        = outgoingMessagesRichTextBox.Text;
                    string sourceTextLanguage = outgoingLangComboBox.Text;

                    try
                    {
                        var result = _flowClientWorker.SendMessage(
                            recipient: recipient,
                            messageText: messageBody,
                            messageTextLang: sourceTextLanguage);

                        if (result.Success)
                        {
                            try
                            {
                                ZPlay player = new ZPlay();

                                if (player.OpenFile(@"Resources/Sent2.mp3", TStreamFormat.sfAutodetect))
                                {
                                    player.SetMasterVolume(100, 100);
                                    player.SetPlayerVolume(100, 100);

                                    player.StartPlayback();
                                }
                            }
                            catch (Exception)
                            {
                                // I don't care if soundplayer is dgoing crazy
                            }
                            //MessageBox.Show($@"{result.ResponseMessage}");
                            outgoingMessagesRichTextBox.Clear();
                        }
                        else
                        {
                            MessageBox.Show(string.IsNullOrWhiteSpace(result.ResponseMessage)
                                ? "Recipient not found"
                                : result.ResponseMessage);
                        }
                    }
                    catch (Exception exception)
                    {
                        Debug.WriteLine(exception);
                        MessageBox.Show(string.IsNullOrWhiteSpace(exception.Message)
                            ? "Something is wrong: check your server connection"
                            : exception.Message);
                    }
                });
            };

            activateOnlineModeButton.Click += (sender, args) =>
            {
                Task.Run(() =>
                {
                    if (_timer != null)
                    {
                        return;
                    }

                    _timer = new Timer
                    {
                        AutoReset = true,
                        Interval  = 3000
                    };

                    _timer.Elapsed += CheckMailbox;
                    _timer.Start();

                    ((Button)sender).FlatAppearance.BorderColor          = Color.DeepSkyBlue;
                    activateOfflineModeButton.FlatAppearance.BorderColor = Color.Gray;
                });
            };

            activateOfflineModeButton.Click += (sender, args) =>
            {
                Task.Run(() =>
                {
                    if (_timer != null)
                    {
                        _timer.Stop();
                        _timer = null;
                    }

                    ((Button)sender).FlatAppearance.BorderColor         = Color.DeepSkyBlue;
                    activateOnlineModeButton.FlatAppearance.BorderColor = Color.Gray;
                });
            };
        }