private void HandlePlaySongMessage(Message message) { if (message.Payload is Mediafile song) { message.HandledStatus = MessageHandledStatus.HandledCompleted; PlayCommand.Execute(song); } }
/// <summary> /// Plays this instance. /// </summary> public void Play() { if (PlayCommand?.CanExecute(null) == true) { PlayCommand?.Execute(null); MediaState = MediaState.Playing; OnMediaStateChanged(); } }
void HandlePlaySongMessage(Message message) { if (message.Payload is Mediafile) { var song = message.Payload as Mediafile; if (message != null) { message.HandledStatus = MessageHandledStatus.HandledCompleted; } if (song != null) { PlayCommand.Execute(song); } } }
public async Task ExecuteWithNoStation() { var log = A.Fake <ILogger>(); var radio = A.Fake <IRadio>(); var stationProvider = A.Fake <IStationProvider>(); var provider = A.Fake <IConfigurationProvider>(); A.CallTo(() => stationProvider.Search(0)).Returns <Station>(null); var command = new PlayCommand(log, s => { }, stationProvider, provider, radio); var result = await command.Execute(new string[] { "0" }); Assert.Equal(CommandResult.Error, result); }
public async Task ExecuteWithValue() { var log = A.Fake <ILogger>(); var radio = A.Fake <IRadio>(); var stationProvider = A.Fake <IStationProvider>(); var provider = A.Fake <IConfigurationProvider>(); A.CallTo(() => stationProvider.Search(0)).Returns(new Station { Uri = new[] { "http:://test" } }); var command = new PlayCommand(log, s => { }, stationProvider, provider, radio); var result = await command.Execute(new string[] { "0" }); A.CallTo(() => radio.Play(A <string> .That.IsEqualTo("http:://test"))).MustHaveHappened(); Assert.Equal(CommandResult.OK, result); }
private void PlayPauseButton_Click(object sender, RoutedEventArgs e) { if (!MediaPlaying) { Play(); if (PlayCommand != null && PlayCommand.CanExecute(EMPTY_PARAMETER)) { PlayCommand.Execute(EMPTY_PARAMETER); } } else { Pause(); if (PauseCommand != null && PauseCommand.CanExecute(EMPTY_PARAMETER)) { PauseCommand.Execute(EMPTY_PARAMETER); } } }
public async Task ExecuteWithoutValue() { var log = A.Fake <ILogger>(); var radio = A.Fake <IRadio>(); var stationProvider = A.Fake <IStationProvider>(); var provider = A.Fake <IConfigurationProvider>(); var configuration = new Configuration() { DefaultLink = "http:://test" }; A.CallTo(() => provider.Load()).Returns(Task.FromResult(configuration)); var command = new PlayCommand(log, s => { }, stationProvider, provider, radio); var result = await command.Execute(new string[0]); A.CallTo(() => radio.Play(A <string> .That.IsEqualTo("http:://test"))).MustHaveHappened(); Assert.Equal(CommandResult.OK, result); }
/// <summary> /// Initializes the mouse events for the window. /// </summary> private void InitializeInputEvents() { #region Allow Keyboard Control var togglePlayPauseKeys = new[] { Key.Play, Key.MediaPlayPause, Key.Space }; window.PreviewKeyDown += async(s, e) => { // Console.WriteLine($"KEY: {e.Key}, SRC: {e.OriginalSource?.GetType().Name}"); if (e.OriginalSource is TextBox) { return; } // Keep the key focus on the main window FocusManager.SetIsFocusScope(this, true); FocusManager.SetFocusedElement(this, this); // Pause if (togglePlayPauseKeys.Contains(e.Key) && Media.IsPlaying) { PauseCommand.Execute(); return; } // Play if (togglePlayPauseKeys.Contains(e.Key) && Media.IsPlaying == false) { PlayCommand.Execute(); return; } // Seek to left if (e.Key == Key.Left) { if (Media.IsPlaying) { await Media.Pause(); } Media.Position -= Media.FrameStepDuration; } // Seek to right if (e.Key == Key.Right) { if (Media.IsPlaying) { await Media.Pause(); } Media.Position += Media.FrameStepDuration; } // Volume Up if (e.Key == Key.Add || e.Key == Key.VolumeUp) { Media.Volume += 0.05; return; } // Volume Down if (e.Key == Key.Subtract || e.Key == Key.VolumeDown) { Media.Volume -= 0.05; return; } // Mute/Unmute if (e.Key == Key.M || e.Key == Key.VolumeMute) { Media.IsMuted = !Media.IsMuted; return; } // Increase speed if (e.Key == Key.Up) { Media.SpeedRatio += 0.05; return; } // Decrease speed if (e.Key == Key.Down) { Media.SpeedRatio -= 0.05; return; } // Reset changes if (e.Key == Key.R) { Media.SpeedRatio = 1.0; Media.Volume = 1.0; Media.Balance = 0; Media.IsMuted = false; } }; #endregion #region Toggle Fullscreen with Double Click Media.PreviewMouseDoubleClick += (s, e) => { if (s != Media) { return; } e.Handled = true; ToggleFullscreenCommand.Execute(); }; #endregion #region Exit fullscreen with Escape key PreviewKeyDown += (s, e) => { if (e.Key == Key.Escape && WindowStyle == WindowStyle.None) { e.Handled = true; ToggleFullscreenCommand.Execute(); } }; #endregion #region Handle Zooming with Mouse Wheel MouseWheel += (s, e) => { if (Media.IsOpen == false || Media.IsOpening) { return; } var delta = (e.Delta / 2000d).ToMultipleOf(0.05d); MediaZoom = Math.Round(MediaZoom + delta, 2); }; UrlTextBox.PreviewMouseWheel += (s, e) => { e.Handled = true; }; #endregion #region Handle Play Pause with Mouse Clicks /* * Media.PreviewMouseDown += (s, e) => * { * if (s != Media) return; * if (Media.IsOpen == false || Media.CanPause == false) return; * if (Media.IsPlaying) * PauseCommand.Execute(); * else * PlayCommand.Execute(); * }; */ #endregion #region Mouse Move Handling (Hide and Show Controls) LastMouseMoveTime = DateTime.UtcNow; MouseMove += (s, e) => { var currentPosition = e.GetPosition(window); if (currentPosition.X != LastMousePosition.X || currentPosition.Y != LastMousePosition.Y) { LastMouseMoveTime = DateTime.UtcNow; } LastMousePosition = currentPosition; }; MouseLeave += (s, e) => { LastMouseMoveTime = DateTime.UtcNow.Subtract(TimeSpan.FromSeconds(10)); }; var mouseMoveTimer = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromMilliseconds(150), IsEnabled = true }; mouseMoveTimer.Tick += (s, e) => { var elapsedSinceMouseMove = DateTime.UtcNow.Subtract(LastMouseMoveTime); if (elapsedSinceMouseMove.TotalMilliseconds >= 3000 && Media.IsOpen && Controls.IsMouseOver == false && OpenMediaPopup.IsOpen == false && DebugWindowPopup.IsOpen == false && SoundMenuPopup.IsOpen == false) { if (Controls.Opacity != 0d) { Cursor = System.Windows.Input.Cursors.None; var sb = Player.FindResource("HideControlOpacity") as Storyboard; Storyboard.SetTarget(sb, Controls); sb.Begin(); } } else { if (Controls.Opacity != 1d) { Cursor = System.Windows.Input.Cursors.Arrow; var sb = Player.FindResource("ShowControlOpacity") as Storyboard; Storyboard.SetTarget(sb, Controls); sb.Begin(); } } }; mouseMoveTimer.Start(); #endregion }
public Example2ViewModel(Window window) { _libVLC = new LibVLC(); MediaPlayer = new MediaPlayer(_libVLC); bool operationActive = false; var refresh = new Subject <Unit>(); //disable events while some operations active, as sometimes causing deadlocks IObservable <Unit> Wrap(IObservable <Unit> obs) => obs.Where(_ => !operationActive).Merge(refresh).ObserveOn(AvaloniaScheduler.Instance); IObservable <Unit> VLCEvent(string name) => Observable.FromEventPattern(MediaPlayer, name).Select(_ => Unit.Default); void Op(Action action) { operationActive = true; action(); operationActive = false; refresh.OnNext(Unit.Default); }; var positionChanged = VLCEvent(nameof(MediaPlayer.PositionChanged)); var playingChanged = VLCEvent(nameof(MediaPlayer.Playing)); var stoppedChanged = VLCEvent(nameof(MediaPlayer.Stopped)); var timeChanged = VLCEvent(nameof(MediaPlayer.TimeChanged)); var lengthChanged = VLCEvent(nameof(MediaPlayer.LengthChanged)); var muteChanged = VLCEvent(nameof(MediaPlayer.Muted)) .Merge(VLCEvent(nameof(MediaPlayer.Unmuted))); var endReachedChanged = VLCEvent(nameof(MediaPlayer.EndReached)); var pausedChanged = VLCEvent(nameof(MediaPlayer.Paused)); var volumeChanged = VLCEvent(nameof(MediaPlayer.VolumeChanged)); var stateChanged = Observable.Merge(playingChanged, stoppedChanged, endReachedChanged, pausedChanged); var hasMediaObservable = this.WhenAnyValue(v => v.MediaUrl, v => !string.IsNullOrEmpty(v)); var fullState = Observable.Merge( stateChanged, VLCEvent(nameof(MediaPlayer.NothingSpecial)), VLCEvent(nameof(MediaPlayer.Buffering)), VLCEvent(nameof(MediaPlayer.EncounteredError)) ); _subscriptions = new CompositeDisposable { Wrap(positionChanged).DistinctUntilChanged(_ => Position).Subscribe(_ => this.RaisePropertyChanged(nameof(Position))), Wrap(timeChanged).DistinctUntilChanged(_ => CurrentTime).Subscribe(_ => this.RaisePropertyChanged(nameof(CurrentTime))), Wrap(lengthChanged).DistinctUntilChanged(_ => Duration).Subscribe(_ => this.RaisePropertyChanged(nameof(Duration))), Wrap(muteChanged).DistinctUntilChanged(_ => IsMuted).Subscribe(_ => this.RaisePropertyChanged(nameof(IsMuted))), Wrap(fullState).DistinctUntilChanged(_ => State).Subscribe(_ => this.RaisePropertyChanged(nameof(State))), Wrap(volumeChanged).DistinctUntilChanged(_ => Volume).Subscribe(_ => this.RaisePropertyChanged(nameof(Volume))), Wrap(fullState).DistinctUntilChanged(_ => Information).Subscribe(_ => this.RaisePropertyChanged(nameof(Information))) }; bool active() => _subscriptions == null ? false : MediaPlayer.IsPlaying || MediaPlayer.CanPause; stateChanged = Wrap(stateChanged); PlayCommand = ReactiveCommand.Create( () => Op(() => { string absolute = new Uri(MediaUrl).AbsoluteUri; bool isfile = absolute.StartsWith("file://"); MediaPlayer.Media = new Media(_libVLC, MediaUrl, isfile ? FromType.FromPath : FromType.FromLocation); MediaPlayer.Play(); }), hasMediaObservable); StopCommand = ReactiveCommand.Create( () => Op(() => MediaPlayer.Stop()), stateChanged.Select(_ => active())); PauseCommand = ReactiveCommand.Create( () => MediaPlayer.Pause(), stateChanged.Select(_ => active())); ForwardCommand = ReactiveCommand.Create( () => MediaPlayer.Time += 1000, stateChanged.Select(_ => active())); BackwardCommand = ReactiveCommand.Create( () => MediaPlayer.Time -= 1000, stateChanged.Select(_ => active())); NextFrameCommand = ReactiveCommand.Create( () => MediaPlayer.NextFrame(), stateChanged.Select(_ => active())); OpenCommand = ReactiveCommand.CreateFromTask(async() => { var fd = new OpenFileDialog() { AllowMultiple = false }; var res = await fd.ShowAsync(window); if (res.Any()) { MediaUrl = res.FirstOrDefault(); Dispatcher.UIThread.InvokeAsync(() => PlayCommand.Execute(null)); } }); MediaUrl = "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"; Wrap(playingChanged).Subscribe(_ => { if (!_played.Contains(MediaUrl)) { _played.Add(MediaUrl); SavePlayed(); } }); }
private static void Main(string[] args) { var record = new Command("rec") { new Argument <FileInfo>("file") { Description = "The filename to save the record" }, new Option(new [] { "--command", "-c" }, "The command to record, default to be powershell.exe", typeof(string)) }; record.Description = "Record and save a session"; record.Handler = CommandHandler.Create((FileInfo file, string command) => { var recordCmd = new RecordCommand(new RecordArgs { Filename = file.FullName, Command = command }); recordCmd.Execute(); }); var play = new Command("play") { new Argument <FileInfo>("file") { Description = "The record session" } }; play.Description = "Play a recorded session"; play.Handler = CommandHandler.Create((FileInfo file) => { var playCommand = new PlayCommand(new PlayArgs { Filename = file.FullName, EnableAnsiEscape = true }); playCommand.Execute(); }); var auth = new Command("auth") { Handler = CommandHandler.Create(() => { var authCommand = new AuthCommand(); authCommand.Execute(); }), Description = "Auth with asciinema.org" }; var upload = new Command("upload") { new Argument <FileInfo>("file") { Description = "The file to be uploaded" } }; upload.Description = "Upload a session to ascinema.org"; upload.Handler = CommandHandler.Create((FileInfo file) => { var uploadCommand = new UploadCommand(file.FullName); uploadCommand.Execute(); }); var rooCommand = new RootCommand { record, play, auth, upload }; rooCommand.Description = "Record, Play and Share your PowerShell Session."; rooCommand.InvokeAsync(args).Wait(); }
private void OnPlayClicked() { PlayClicked?.Invoke(this, EventArgs.Empty); PlayCommand?.Execute(null); }
private void PlayButton_OnPlayClicked(object sender, EventArgs e) { PlayCommand?.Execute(null); }
/// <summary> /// Process the game. /// </summary> /// <param name="playBoard">Current play board value.</param> /// <param name="playerMoves">Current player moves.</param> public void ProcessGame(ref char[,] playBoard, ref int playerMoves) { byte rowLenght = (byte)playBoard.GetLength(0); byte columnLenght = (byte)playBoard.GetLength(1); Board boardGenerator = new Board(rowLenght, columnLenght); ScoreBoardFormatter formatter = new ScoreBoardFormatter(); // ILogger fileLogger = new FileLogger("scorebord.txt", formatter); ILogger consoleLogger = new ConsoleLogger(formatter); ScoreBoard scoreBoard = new ScoreBoard(consoleLogger); var printer = PrintingManager.Instance; switch (this.currentCommand) { case "RESTART": IInputCommand restart = new RestartCommand(boardGenerator, printer); restart.Execute(ref playBoard, ref playerMoves); break; case "TOP": IInputCommand topscoreBoard = new TopCommand(scoreBoard, this.topPlayers); topscoreBoard.Execute(ref playBoard, ref playerMoves); break; case "EXIT": break; default: InputCommandValidator validator = new InputCommandValidator(); if (validator.IsValidInputCommand(this.currentCommand)) { IInputCommand play = new PlayCommand(this.currentCommand, this.topPlayers, scoreBoard, boardGenerator, printer); play.Execute(ref playBoard, ref playerMoves); break; } Console.WriteLine("Wrong input ! Try Again ! "); break; } }