public void PlayFile(string path) { try { if (!File.Exists(path)) { if (PlayFinishedEvent != null) { PlayFinishedEvent(this, EventArgs.Empty); } } if (image != null) image.Dispose(); image = new Bitmap(path); state = PlayState.Running; tickcount = 0; Refresh(); } catch (Exception exp) { if (PlayFinishedEvent != null) { PlayFinishedEvent(this, EventArgs.Empty); } } }
public WaveSoundPlayer(WaveFile w, bool loop) { ac = new AudioContext (); bufferlist = new List<int> (NUM_BUFFERS); bufferlist.AddRange (AL.GenBuffers (NUM_BUFFERS)); source = AL.GenSource (); this._PlayState = PlayState.NotLoaded; wfile = w; bufferlist.ForEach (x => { byte[] buf = new byte[BUFFER_SIZE]; buf = wfile.DataBinary.ReadBytes(BUFFER_SIZE); AL.BufferData(x,wfile.SoundFormat,buf,buf.Length,wfile.SampleRate); }); AL.SourceQueueBuffers (source, NUM_BUFFERS, bufferlist.ToArray ()); if (loop) AL.Source (source, ALSourceb.Looping, true); System.Diagnostics.Debug.WriteLine (AL.GetSourceState(source).ToString()); this._PlayState = PlayState.Stopped; }
void Start() { CameraScript.LoadData(); State = PlayState.menu; //LUCE A SECONDA DELLA PIATTAFORMA if (Application.platform == RuntimePlatform.WP8Player #if UNITY_IPHONE || iPhone.generation == iPhoneGeneration.iPodTouch4Gen || iPhone.generation == iPhoneGeneration.iPodTouch3Gen || iPhone.generation == iPhoneGeneration.iPodTouch2Gen || iPhone.generation == iPhoneGeneration.iPodTouch1Gen || iPhone.generation == iPhoneGeneration.iPhone3GS || iPhone.generation == iPhoneGeneration.iPhone4 || iPhone.generation == iPhoneGeneration.iPad2Gen || iPhone.generation == iPhoneGeneration.iPad1Gen #endif ) { pglight.SetActive(false); wplight.SetActive(true); } else { wplight.SetActive(true); wplight.light.range=6f; pglight.SetActive(true); } GameCredits = 0; }
/// <summary> /// Called when the playstate changes, except for the Error state (see OnError) /// </summary> /// <param name="player">The BackgroundAudioPlayer</param> /// <param name="track">The track playing at the time the playstate changed</param> /// <param name="playState">The new playstate of the player</param> /// <remarks> /// Play State changes cannot be cancelled. They are raised even if the application /// caused the state change itself, assuming the application has opted-in to the callback. /// Notable playstate events: /// (a) TrackEnded: invoked when the player has no current track. The agent can set the next track. /// (b) TrackReady: an audio track has been set and it is now ready for playack. /// Call NotifyComplete() only once, after the agent request has been completed, including async callbacks. /// </remarks> protected override void OnPlayStateChanged(BackgroundAudioPlayer player, AudioTrack track, PlayState playState) { Debug.WriteLine("OnPlayStateChanged() playState " + playState); switch (playState) { case PlayState.TrackEnded: player.Track = GetPreviousTrack(); break; case PlayState.TrackReady: player.Play(); break; case PlayState.Shutdown: // TODO: Handle the shutdown state here (e.g. save state) break; case PlayState.Unknown: break; case PlayState.Stopped: break; case PlayState.Paused: break; case PlayState.Playing: break; case PlayState.BufferingStarted: break; case PlayState.BufferingStopped: break; case PlayState.Rewinding: break; case PlayState.FastForwarding: break; } NotifyComplete(); }
/// <summary> /// playstate 更改时调用,但 Error 状态除外(参见 OnError) /// </summary> /// <param name="player">BackgroundAudioPlayer</param> /// <param name="track">在 playstate 更改时播放的曲目</param> /// <param name="playState">播放机的新 playstate </param> /// <remarks> /// 无法取消播放状态更改。即使应用程序 /// 导致状态自行更改也会提出这些更改,假定应用程序已经选择了回调。 /// /// 值得注意的 playstate 事件: /// (a) TrackEnded: 播放器没有当前曲目时激活。代理可设置下一曲目。 /// (b) TrackReady: 音轨已设置完毕,现在可以播放。 /// /// 只在代理请求完成之后调用一次 NotifyComplete(),包括异步回调。 /// </remarks> protected override void OnPlayStateChanged(BackgroundAudioPlayer player, AudioTrack track, PlayState playState) { switch (playState) { case PlayState.TrackEnded: //player.Track = GetPreviousTrack(); //player.Track = GetNextTrack(); PlayNextTrack(player); break; case PlayState.TrackReady: player.Play(); break; case PlayState.Shutdown: // TODO: 在此处理关机状态(例如保存状态) break; case PlayState.Unknown: break; case PlayState.Stopped: break; case PlayState.Paused: break; case PlayState.Playing: break; case PlayState.BufferingStarted: break; case PlayState.BufferingStopped: break; case PlayState.Rewinding: break; case PlayState.FastForwarding: break; } NotifyComplete(); }
/// <summary> /// Called when the playstate changes, except for the Error state (see OnError) /// </summary> /// <param name="player">The BackgroundAudioPlayer</param> /// <param name="track">The track playing at the time the playstate changed</param> /// <param name="playState">The new playstate of the player</param> /// <remarks> /// Play State changes cannot be cancelled. They are raised even if the application /// caused the state change itself, assuming the application has opted-in to the callback. /// /// Notable playstate events: /// (a) TrackEnded: invoked when the player has no current track. The agent can set the next track. /// (b) TrackReady: an audio track has been set and it is now ready for playack. /// /// Call NotifyComplete() only once, after the agent request has been completed, including async callbacks. /// </remarks> protected override void OnPlayStateChanged(BackgroundAudioPlayer player, AudioTrack track, PlayState playState) { switch (playState) { case PlayState.TrackEnded: player.Track = GetNextTrack(); break; case PlayState.TrackReady: player.Play(); break; case PlayState.Shutdown: // TODO: Handle the shutdown state here (e.g. save state) break; case PlayState.Unknown: break; case PlayState.Stopped: _playlistHelper.SetAllTracksToNotPlayingAndSave(); break; case PlayState.Paused: break; case PlayState.Playing: break; case PlayState.BufferingStarted: break; case PlayState.BufferingStopped: break; case PlayState.Rewinding: break; case PlayState.FastForwarding: break; } NotifyComplete(); }
public VideoService( Rectangle viewFinder, MediaElement player ) { // Initial State _State = PlayState.Paused; _CanRecord = false; _Record = new SwitchableCommand(OnRecord); _Play = new SwitchableCommand(OnPlay); _Stop = new SwitchableCommand(OnPause); _ViewFinder = viewFinder; _Player = player; _Player.MediaEnded += MediaEnded; _CaptureSource = new CaptureSource(); _CaptureSource.CaptureFailed += CaptureFailed; _FileSink = new FileSink(); _Brush = new VideoBrush(); _HasRecording = new BehaviorSubject<bool>(false); }
public MovieScreen() { InitializeComponent(); movie_timer = new Timer(); movie_timer.Tick += new EventHandler(movie_timer_Tick); play_state = PlayState.Close; }
public void Run() { // Start previewing video data int hr = this.mediaControl.Run(); DsError.ThrowExceptionForHR(hr); // Remember current state this.currentState = PlayState.Running; }
protected override void OnPlayStateChanged(BackgroundAudioPlayer player, AudioTrack track, PlayState playState) { switch (playState) { case PlayState.TrackReady: player.Play(); break; } NotifyComplete(); }
public override void Initialize() { base.Initialize(); playState = PlayState.running; spelObjektLista.Clear(); gubbe = game.Player1; gubbe.Initialize(this); spelObjektLista.Add(gubbe); }
public LevelState(Game1 game, Sprite spriteSheet) : base(game) { this.spriteSheet = spriteSheet; font = game.Content.Load<SpriteFont>("vanligFont"); random1 = new Random(); Sprite tile = new Sprite(game.Content.Load<Texture2D>("Tiles/MudTile")); backgroundSprite = new BackgroundSprite(game.Window.ClientBounds.Width, game.Window.ClientBounds.Height, tile); playState = PlayState.running; }
/// <summary> /// Called when the playstate changes, except for the Error state (see OnError) /// </summary> /// <param name="player">The BackgroundAudioPlayer</param> /// <param name="track">The track playing at the time the playstate changed</param> /// <param name="playState">The new playstate of the player</param> /// <remarks> /// Play State changes cannot be cancelled. They are raised even if the application /// caused the state change itself, assuming the application has opted-in to the callback. /// /// Notable playstate events: /// (a) TrackEnded: invoked when the player has no current track. The agent can set the next track. /// (b) TrackReady: an audio track has been set and it is now ready for playack. /// /// Call NotifyComplete() only once, after the agent request has been completed, including async callbacks. /// </remarks> protected override void OnPlayStateChanged(BackgroundAudioPlayer player, AudioTrack track, PlayState playState) { switch (playState) { case PlayState.TrackEnded: //player.Track = GetPreviousTrack(); player.Track = null; break; case PlayState.TrackReady: player.Play(); connectedEvent.Set(); if (track != null && track.Tag != null) { var data = track.Tag.ToString().Split('$'); var url = data[data.Length - 1]; var title = data[1]; var type = data[2]; //#region from http://stackoverflow.com/questions/7159900/detect-application-launch-from-universal-volume-control //MediaHistoryItem nowPlaying = new MediaHistoryItem(); //nowPlaying.Title = title; //nowPlaying.PlayerContext.Add("station", title); //MediaHistory.Instance.NowPlaying = nowPlaying; //#endregion } break; case PlayState.Shutdown: // TODO: Handle the shutdown state here (e.g. save state) break; case PlayState.Unknown: break; case PlayState.Stopped: break; case PlayState.Paused: break; case PlayState.Playing: break; case PlayState.BufferingStarted: break; case PlayState.BufferingStopped: break; case PlayState.Rewinding: break; case PlayState.FastForwarding: break; } NotifyComplete(); }
/// <summary> /// Called when the playstate changes, except for the Error state (see OnError) /// </summary> /// <param name="player">The BackgroundAudioPlayer</param> /// <param name="track">The track playing at the time the playstate changed</param> /// <param name="playState">The new playstate of the player</param> /// <remarks> /// Play State changes cannot be cancelled. They are raised even if the application /// caused the state change itself, assuming the application has opted-in to the callback. /// /// Notable playstate events: /// (a) TrackEnded: invoked when the player has no current track. The agent can set the next track. /// (b) TrackReady: an audio track has been set and it is now ready for playack. /// /// Call NotifyComplete() only once, after the agent request has been completed, including async callbacks. /// </remarks> protected override void OnPlayStateChanged(BackgroundAudioPlayer player, AudioTrack track, PlayState playState) { switch (playState) { case PlayState.TrackReady: // Wiedergabe wurde in PlayTrack() bereits festgelegt player.Play(); break; case PlayState.TrackEnded: PlayNextTrack(player); break; } NotifyComplete(); }
public Metronome() { mTempo = 100; mBeatsPerBar = 4; mMillisecondsBetweenBeats = 60000f / mTempo; mStopAfter = 100; mIncreaseAfter = 16; mIncreaseBy = 10; mIncreaseUpTo = 200; mTickCounter = 0; mPlayState = PlayState.Stopped; mPlayTimer = TimeSpan.Zero; mUpperTempoLimit = 500; mSpeedTemplates = new List<SpeedTemplate>(); mRudiments = new List<Rudiment>(); }
public override bool Play(string strFile) { m_iVolume = 100; m_bNotifyPlaying = true; m_state = PlayState.Init; m_strCurrentFile = strFile; VideoRendererStatistics.VideoState = VideoRendererStatistics.State.VideoPresent; Log.Info("AudioPlayerVMR7.play {0}", strFile); lock (typeof (AudioPlayerVMR7)) { CloseInterfaces(); if (!GetInterfaces()) { m_strCurrentFile = ""; return false; } int hr = mediaEvt.SetNotifyWindow(GUIGraphicsContext.ActiveForm, WM_GRAPHNOTIFY, IntPtr.Zero); if (hr < 0) { m_strCurrentFile = ""; CloseInterfaces(); return false; } GetFrameStepInterface(); _rotEntry = new DsROTEntry((IFilterGraph)graphBuilder); hr = mediaCtrl.Run(); if (hr < 0) { m_strCurrentFile = ""; CloseInterfaces(); return false; } // mediaPos.put_CurrentPosition(4*60); GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_PLAYBACK_STARTED, 0, 0, 0, 0, 0, null); msg.Label = strFile; GUIWindowManager.SendThreadMessage(msg); } m_state = PlayState.Playing; return true; }
protected override void OnPlayStateChanged(BackgroundAudioPlayer player, AudioTrack track, PlayState playState) { switch (playState) { case PlayState.TrackEnded: player.Close(); break; case PlayState.TrackReady: player.Volume = 1.0; player.Play(); break; case PlayState.Shutdown: // TODO: Handle the shutdown state here (e.g. save state) break; case PlayState.Unknown: break; case PlayState.Stopped: break; case PlayState.Paused: break; case PlayState.Playing: break; case PlayState.BufferingStarted: break; case PlayState.BufferingStopped: break; case PlayState.Rewinding: break; case PlayState.FastForwarding: break; } NotifyComplete(); }
/// <summary> /// Called when the playstate changes, except for the Error state (see OnError) /// </summary> /// <param name="player">The BackgroundAudioPlayer</param> /// <param name="track">The track playing at the time the playstate changed</param> /// <param name="playState">The new playstate of the player</param> /// <remarks> /// Play State changes cannot be cancelled. They are raised even if the application /// caused the state change itself, assuming the application has opted-in to the callback. /// /// Notable playstate events: /// (a) TrackEnded: invoked when the player has no current track. The agent can set the next track. /// (b) TrackReady: an audio track has been set and it is now ready for playack. /// /// Call NotifyComplete() only once, after the agent request has been completed, including async callbacks. /// </remarks> protected override void OnPlayStateChanged(BackgroundAudioPlayer player, AudioTrack track, PlayState playState) { switch (playState) { case PlayState.TrackEnded: //player.Track = GetPreviousTrack(); if (currentTrack < playlist.Count - 1) { currentTrack += 1; player.Track = playlist[currentTrack]; } else { player.Track = null; } break; case PlayState.TrackReady: player.Play(); break; case PlayState.Shutdown: // TODO: Handle the shutdown state here (e.g. save state) break; case PlayState.Unknown: break; case PlayState.Stopped: break; case PlayState.Paused: break; case PlayState.Playing: break; case PlayState.BufferingStarted: break; case PlayState.BufferingStopped: break; case PlayState.Rewinding: break; case PlayState.FastForwarding: break; } NotifyComplete(); }
// Update is called once per frame void Update () { if ( Input.GetButtonDown( "Menu" ) ) { ToggleMainMenu(); } if ( currentState == GameState.Playing ) { gameTime += Time.deltaTime; zombieTime += Time.deltaTime; //spawn zombies if ( zombieTime > zombieSpawnRate ) { zombieTime = 0.0f; //zombieSpawner.RandomSpawn(); } // update playing state switch ( currentPlayState ) { case PlayState.Start: if ( gameTime > requestTime ) { player.radio.RadioRequest(); currentPlayState = PlayState.Request; } break; case PlayState.Request: if ( gameTime > inboundTime ) { player.radio.RadioInbound(); currentPlayState = PlayState.Inbound; } break; case PlayState.Inbound: if ( gameTime > landedTime ) { player.radio.RadioLanded(); currentPlayState = PlayState.Landed; } break; case PlayState.Landed: break; } } }
/// <summary> /// Called when the playstate changes, except for the Error state (see OnError) /// </summary> /// <param name="player">The BackgroundAudioPlayer</param> /// <param name="track">The track playing at the time the playstate changed</param> /// <param name="playState">The new playstate of the player</param> /// <remarks> /// Play State changes cannot be cancelled. They are raised even if the application /// caused the state change itself, assuming the application has opted-in to the callback /// </remarks> protected override void OnPlayStateChanged(BackgroundAudioPlayer player, AudioTrack track, PlayState playState) { switch (playState) { case PlayState.TrackReady: // The track to play is set in the PlayTrack method. player.Volume = 1; player.Play(); break; case PlayState.TrackEnded: try { player.Stop(); } catch (Exception e) { //Console.WriteLine(e); } break; } NotifyComplete(); }
public void CompareValue(int numberCounted) { gameState = PlayState.Validate; if (numberCounted == HouseBehaviour.Instance.In) { ShowPanels.Instance.HideAll(); ShowPanels.Instance.ShowWin(); } else { ShowPanels.Instance.HideAll(); ShowPanels.Instance.ShowLose(); solution.text = HouseBehaviour.Instance.In.ToString(); } foreach (GameObject guests in CharacterGenerator.Instance.ListedGuest) { guests.tag = "Out"; guests.SetActive(true); } }
public void ChangeScene(PlayState newState) { Instantiate(GarageFadeObject, MainCanvas.transform); StartCoroutine(SceneFade(newState)); }
public AudioPlayerStateChanged(PlayState state) { this.PlayState = state; }
public void Play() { _state = PlayState.PLAYING; }
public void CaptureVideo() { int hr = 0; try { // Get DirectShow interfaces GetInterfaces(); // Attach the filter graph to the capture graph hr = this.captureGraphBuilder.SetFiltergraph(this.graphBuilder); DsError.ThrowExceptionForHR(hr); // Use the system device enumerator and class enumerator to find // a video capture/preview device, such as a desktop USB video camera. sourceFilter = FindCaptureDevice(); IAMAnalogVideoDecoder decoder = sourceFilter as IAMAnalogVideoDecoder; if (decoder != null) { AnalogVideoStandard oldStandard; decoder.get_TVFormat(out oldStandard); if (oldStandard != AnalogVideoStandard.NTSC_M) { decoder.put_TVFormat(AnalogVideoStandard.NTSC_M); } decoder = null; } AdjustCrossbarPin(); // Add Capture filter to our graph. hr = this.graphBuilder.AddFilter(sourceFilter, "Video Capture"); DsError.ThrowExceptionForHR(hr); // Render the preview pin on the video capture filter // Use this instead of this.graphBuilder.RenderFile hr = this.captureGraphBuilder.RenderStream(PinCategory.Preview, MediaType.Video, sourceFilter, null, null); DsError.ThrowExceptionForHR(hr); // Now that the filter has been added to the graph and we have // rendered its stream, we can release this reference to the filter. Marshal.ReleaseComObject(sourceFilter); // Set video window style and position SetupVideoWindow(); // Add our graph to the running object table, which will allow // the GraphEdit application to "spy" on our graph rot = new DsROTEntry(this.graphBuilder); // Start previewing video data hr = this.mediaControl.Run(); DsError.ThrowExceptionForHR(hr); // Remember current state this.currentState = PlayState.Running; } catch { MessageBox.Show("An unrecoverable error has occurred."); } }
public override PlayState getPlayState() { PlayState ret = (PlayState)Audio360CSharpPINVOKE.SpatDecoderInterface_getPlayState(swigCPtr); return(ret); }
/// <summary> /// Called when the playstate changes, except for the Error state (see OnError) /// </summary> /// <param name="player">The BackgroundAudioPlayer</param> /// <param name="track">The track playing at the time the playstate changed</param> /// <param name="playState">The new playstate of the player</param> /// <remarks> /// Play State changes cannot be cancelled. They are raised even if the application /// caused the state change itself, assuming the application has opted-in to the callback. /// /// Notable playstate events: /// (a) TrackEnded: invoked when the player has no current track. The agent can set the next track. /// /// Call NotifyComplete() only once, after the agent request has been completed, including async callbacks. /// </remarks> protected override void OnPlayStateChanged(BackgroundAudioPlayer player, AudioTrack track, PlayState playState) { switch (playState) { case PlayState.TrackEnded: PlayNextTrack(player); break; } NotifyComplete(); }
/// <summary> /// Called when the playstate changes, except for the Error state (see OnError) /// </summary> /// <param name="player">The BackgroundAudioPlayer</param> /// <param name="track">The track playing at the time the playstate changed</param> /// <param name="playState">The new playstate of the player</param> /// <remarks> /// /// Play State changes cannot be cancelled. They are raised even if the application /// caused the state change itself, assuming the application has opted-in to the callback. /// /// Notable playstate events: /// (a) TrackEnded: invoked when the player has no current track. The agent can set the next track. /// (b) TrackReady: an audio track has been set and it is now ready for playack. /// /// Call NotifyComplete() only once, after the agent request has been completed, including async callbacks. /// </remarks> protected override void OnPlayStateChanged(BackgroundAudioPlayer player, AudioTrack track, PlayState playState) { switch (playState) { case PlayState.TrackEnded: Func <List <GuidToTrackMapping>, AudioTrack, GuidToTrackMapping> defineNextTrackPredicate = (mappings, currentTrack) => { var index = mappings.IndexOf(mappings.Single(o => o.Guid == new Guid(currentTrack.Tag))); index++; if (index >= mappings.Count) { // no random, no repeat ! return(null); } return(new GuidToTrackMapping { Guid = mappings[index].Guid, Track = mappings[index].Track }); }; player.Track = GetNextTrack(track, defineNextTrackPredicate); break; case PlayState.TrackReady: player.Play(); break; case PlayState.Shutdown: // TODO: Handle the shutdown state here (e.g. save state) break; case PlayState.Unknown: break; case PlayState.Stopped: break; case PlayState.Paused: break; case PlayState.Playing: break; case PlayState.BufferingStarted: break; case PlayState.BufferingStopped: break; case PlayState.Rewinding: break; case PlayState.FastForwarding: break; } NotifyComplete(); }
// Use this for initialization void Start() { play_state = PlayState.paused; canvas = GameObject.FindObjectOfType <Canvas>(); foreach (Button button in canvas.GetComponentsInChildren <Button>()) { switch (button.name) { case "PlayPauseButton": playpause_button = button; break; case "Timestamp": timestamp = button; timestamp_text = timestamp.GetComponentInChildren <Text>(); break; case "ResetPlayback": reset_button = button; break; case "MovieLoader": load_movie_button = button; break; } } foreach (Image image in canvas.GetComponentsInChildren <Image>()) { switch (image.name) { case "FigRenderer": fig_renderer = image.GetComponentInChildren <Image>(); break; case "InterfaceOcclussion": interface_occlussion = image.GetComponentInChildren <Image>(); break; } } foreach (Slider slider in canvas.GetComponentsInChildren <Slider>()) { switch (slider.name) { case "TimeSlider": time_slider = slider; break; case "VolumeSlider": volume_slider = slider; break; } } playpause_button_text = playpause_button.GetComponentInChildren <Text>(); video_time = 0f; frame_time = 0f; frame_has_been_updated = false; natural_progression = false; playback_speed = GameObject.FindObjectOfType <Dropdown>(); audio_source = GameObject.FindObjectOfType <AudioSource>(); scrolling_content = GameObject.Find("Content").GetComponent <RectTransform> (); //scrolling_content.localPosition = new Vector3 (0, 40, 0); is_loading_figs = false; load_status = GameObject.Find("LoadStatus").GetComponentInChildren <Text>(); //load_all_sprites(); //load_figs(); }
/// <summary> /// Called when the playstate changes, except for the Error state (see OnError) /// </summary> /// <param name="player">The BackgroundAudioPlayer</param> /// <param name="track">The track playing at the time the playstate changed</param> /// <param name="playState">The new playstate of the player</param> /// <remarks> /// Play State changes cannot be cancelled. They are raised even if the application /// caused the state change itself, assuming the application has opted-in to the callback. /// /// Notable playstate events: /// (a) TrackEnded: invoked when the player has no current track. The agent can set the next track. /// (b) TrackReady: an audio track has been set and it is now ready for playack. /// /// Call NotifyComplete() only once, after the agent request has been completed, including async callbacks. /// </remarks> protected override void OnPlayStateChanged(BackgroundAudioPlayer player, AudioTrack track, PlayState playState) { switch (playState) { case PlayState.TrackEnded: PlaylistItem currentPlaylistItem = getCurrentlyPlayingTrack(); if (currentPlaylistItem != null) { currentPlaylistItem.SavedPlayPosTick = currentPlaylistItem.TotalPlayTicks; // We hit TrackEnded event so we can save the playpos to the end. // But really, this is a bug in WP8 since the player doesn't know the playpos at this point anymore. updateToDBPlaylistItem(currentPlaylistItem); } // Start playing next track if we have one. AudioTrack nextTrack = getNextPlaylistTrack(); if (nextTrack != null) { player.Track = nextTrack; player.Play(); } else { player.Stop(); } break; case PlayState.TrackReady: break; case PlayState.Shutdown: updatePlayposForCurrentEpisode(player); break; case PlayState.Unknown: updatePlayposForCurrentEpisode(player); Debug.WriteLine("Play state: Unkown"); break; case PlayState.Stopped: updatePlayposForCurrentEpisode(player); clearPrimaryTile(); Debug.WriteLine("Play state: Stopped"); break; case PlayState.Paused: updatePlayposForCurrentEpisode(player); Debug.WriteLine("Play state: Paused"); break; case PlayState.Playing: PlaylistItem plItem = getCurrentlyPlayingTrack(); if (plItem != null) { plItem.TotalPlayTicks = player.Track.Duration.Ticks; updateToDBPlaylistItem(plItem); Debug.WriteLine("Play state: Playing"); } else { Debug.WriteLine("Playlist item NULL!"); } updatePlayposForCurrentEpisode(player); setCurrentlyPlayingTrack(player.Track.Title); break; case PlayState.BufferingStarted: break; case PlayState.BufferingStopped: break; case PlayState.Rewinding: break; case PlayState.FastForwarding: break; } NotifyComplete(); }
private void SelectSong() { OpenFileDialog Open = new OpenFileDialog { Filter = "MP3 Files|*.mp3|CSV Files|*.csv" /*+ "|All Files|*.*"*/, InitialDirectory = SettingsForm.Path(), Multiselect = true }; if (Open.ShowDialog() == DialogResult.OK) { if (Path.GetExtension(Open.FileName) == ".csv") { if (CSV.Import(Open.FileName, ',').ElementAt(0).Length != 1) { _state = PlayState.CSVPlaylist; PlaylistPath = Open.FileName; GlobalPath = Path.GetDirectoryName(PlaylistPath) + "\\"; OriginalSongDetails = Songs(PlaylistPath); //Take full path to .csv and return values SongDetails = new List <string[]>(OriginalSongDetails); OriginalMusic = new List <string>(Filenames()); //List of direct paths to each song Music = new List <string>(OriginalMusic); CurrentSong = 0; _songCount = Music.Count(); string firstSong = Music[CurrentSong]; //Artist - Album.mp3 _choose.URL = firstSong; SetDetails(CurrentSong); _choose.controls.stop(); lblDuration.Text = _choose.currentMedia.durationString; InitializeDefaultSettings(); } else if (CSV.Import(Open.FileName, ',').ElementAt(0).Length == 1) // NOT TESTED { _state = PlayState.CSVFilePlaylist; SongDetails = null; GlobalPath = null; List <string[]> vs = CSV.Import(Open.FileName, ','); OriginalMusic = new List <string>(); foreach (var item in vs) { OriginalMusic.Add(item[0]); } Music = new List <string>(OriginalMusic); CurrentSong = 0; _choose.URL = OriginalMusic.ElementAt(0); SetDetails(OriginalMusic.ElementAt(0)); _choose.controls.stop(); lblDuration.Text = _choose.currentMedia.durationString; InitializeDefaultSettings(); } } else //.mp3 { if (Open.FileNames.Length == 1) { _state = PlayState.OneSong; SongDetails = null; GlobalPath = Path.GetDirectoryName(Open.FileName) + "\\"; OriginalMusic = new List <string>(Open.FileNames); Music = new List <string>(OriginalMusic); CurrentSong = 0; _choose.URL = Open.FileName; SetDetails(Open.FileName); _choose.controls.stop(); lblDuration.Text = _choose.currentMedia.durationString; InitializeDefaultSettings(); } else { _state = PlayState.MultipleSongs; SongDetails = null; GlobalPath = Path.GetDirectoryName(Open.FileName) + "\\"; OriginalMusic = new List <string>(Open.FileNames); Music = new List <string>(OriginalMusic); CurrentSong = 0; _choose.URL = Open.FileNames[CurrentSong]; SetDetails(Open.FileNames[CurrentSong]); _choose.controls.stop(); lblDuration.Text = _choose.currentMedia.durationString; InitializeDefaultSettings(); } } } }
// Use this for initialization void Start() { current_state = new TutorialState(this, tutorial_animator); play_state = new PlayState(this); }
/// <summary> /// Occures, when the mplayer process exists /// </summary> /// <param name="sender">Sender</param> /// <param name="e">EventArguments</param> private void MplayerProcessExited(object sender, EventArgs e) { Log.Info("MPlayer: Player exited"); _playState = PlayState.Ended; }
// Update is called once per frame void Update() { switch (pState) { case PlayState.TITLE: BackButton.SetActive(false); title.SetActive(true); mainMenu.SetActive(false); robotMenu.SetActive(false); robotMenu2.SetActive(false); battleMenu.SetActive(false); combatStuffs.SetActive(false); Manager.GetComponent <SoundList>().SwitchMusic(2); break; case PlayState.TOWN: //Manager.GetComponent<turnManager>().bState = BattleState.END; BackButton.SetActive(true); title.SetActive(false); mainMenu.SetActive(true); robotMenu.SetActive(false); robotMenu2.SetActive(false); battleMenu.SetActive(false); combatStuffs.SetActive(false); if (Input.GetKeyDown(Keys.Menu)) { pState = PlayState.MENU; } if (Input.GetKeyDown(Keys.RobotMenu)) { pState = PlayState.ROBOTMENU; } /* * if (Input.GetKeyDown(KeyCode.B)) * pState = PlayState.BATTLE; */ Manager.GetComponent <SoundList>().SwitchMusic(2); //Manager.GetComponent<RobotCreation>().moneyText.SetActive(false); break; case PlayState.MENU: BackButton.SetActive(true); /* * if (Input.GetKeyDown(Keys.Menu)) * pState = PlayState.TOWN; */ Manager.GetComponent <SoundList>().SwitchMusic(2); break; case PlayState.ROBOTMENU: BackButton.SetActive(true); title.SetActive(false); mainMenu.SetActive(false); robotMenu.SetActive(true); robotMenu2.SetActive(false); battleMenu.SetActive(false); combatStuffs.SetActive(false); /* * if (Input.GetKeyDown(Keys.RobotMenu)) * pState = PlayState.TOWN; */ Manager.GetComponent <SoundList>().SwitchMusic(0); //Manager.GetComponent<RobotCreation>().moneyText.SetActive(true); break; case PlayState.ROBOTMENU2: BackButton.SetActive(true); title.SetActive(false); mainMenu.SetActive(false); robotMenu.SetActive(false); robotMenu2.SetActive(true); battleMenu.SetActive(false); combatStuffs.SetActive(false); /* * if (Input.GetKeyDown(Keys.RobotMenu)) * pState = PlayState.TOWN; */ break; case PlayState.BATTLE: BackButton.SetActive(true); title.SetActive(false); mainMenu.SetActive(false); robotMenu.SetActive(false); robotMenu2.SetActive(false); battleMenu.SetActive(true); combatStuffs.SetActive(true); /* * if (Input.GetKeyDown(Keys.Menu)) * pState = PlayState.TOWN; */ if (Manager.GetComponent <EnemyController>().sState == StageState.ARENA && Manager.GetComponent <EnemyController>().Stage == 3) { Manager.GetComponent <SoundList>().SwitchMusic(3); } else { Manager.GetComponent <SoundList>().SwitchMusic(1); } //Manager.GetComponent<RobotCreation>().moneyText.SetActive(false); break; } }
void Start() { Manager = GameObject.Find("Manager"); pState = PlayState.TITLE; BackButton = GameObject.Find("BackButton"); }
/// <summary> do cleanup and release DirectShow. </summary> protected virtual void CloseDVDInterfaces() { if (_graphBuilder == null) { return; } int hr; try { logger.Info("DVDPlayer:cleanup DShow graph"); if (_mediaCtrl != null) { hr = _mediaCtrl.Stop(); _mediaCtrl = null; } _state = PlayState.Stopped; _mediaEvt = null; _visible = false; _videoWin = null; // videoStep = null; _dvdCtrl = null; _dvdInfo = null; _basicVideo = null; _basicAudio = null; _mediaPos = null; _mediaSeek = null; _mediaStep = null; //if (_vmr7 != null) //{ // _vmr7.RemoveVMR7(); //} //_vmr7 = null; if (_vmr9Filter != null) { while ((hr = DirectShowUtil.ReleaseComObject(_vmr9Filter)) > 0) { ; } _vmr9Filter = null; } if (_dvdbasefilter != null) { while ((hr = DirectShowUtil.ReleaseComObject(_dvdbasefilter)) > 0) { ; } _dvdbasefilter = null; } if (_cmdOption != null) { DirectShowUtil.ReleaseComObject(_cmdOption); } _cmdOption = null; _pendingCmd = false; if (_line21Decoder != null) { while ((hr = DirectShowUtil.ReleaseComObject(_line21Decoder)) > 0) { ; } _line21Decoder = null; } if (_graphBuilder != null) { DirectShowUtil.RemoveFilters(_graphBuilder); if (_rotEntry != null) { _rotEntry.Dispose(); _rotEntry = null; } while ((hr = DirectShowUtil.ReleaseComObject(_graphBuilder)) > 0) { ; } _graphBuilder = null; } if (_dvdGraph != null) { while ((hr = DirectShowUtil.ReleaseComObject(_dvdGraph)) > 0) { ; } _dvdGraph = null; } _state = PlayState.Init; } catch (Exception ex) { logger.Error("DVDPlayer:exception while cleanuping DShow graph {0} {1}", ex.Message, ex.StackTrace); } }
private void InternalStep(PlayState _playState, Func <double, T, T> Interpolator) { if (!_gotFirstKFValue) { _firstKFValue = _parent.First().Value; _gotFirstKFValue = true; } if (_currentState == KeyFramesStates.Disposed) { throw new InvalidProgramException("This KeyFrames Animation is already disposed."); } if (_playState == PlayState.Stop) { _currentState = KeyFramesStates.Stop; } // Save state and pause the machine if (_playState == PlayState.Pause && _currentState != KeyFramesStates.Pause) { _savedState = _currentState; _currentState = KeyFramesStates.Pause; } // Resume the previous state if (_playState != PlayState.Pause && _currentState == KeyFramesStates.Pause) { _currentState = _savedState; } double _tempDuration = 0d, _easedTime; bool handled = false; while (!handled) { switch (_currentState) { case KeyFramesStates.DoDelay: if (_fillMode == FillMode.Backward || _fillMode == FillMode.Both) { if (_currentIteration == 0) { _targetObserver.OnNext(_firstKFValue); } else { _targetObserver.OnNext(_lastInterpValue); } } if (_delayFrameCount > _delayTotalFrameCount) { _currentState = KeyFramesStates.DoRun; } else { handled = true; _delayFrameCount++; } break; case KeyFramesStates.DoRun: if (_isReversed) { _currentState = KeyFramesStates.RunBackwards; } else { _currentState = KeyFramesStates.RunForwards; } break; case KeyFramesStates.RunForwards: if (_durationFrameCount > _durationTotalFrameCount) { _currentState = KeyFramesStates.RunComplete; } else { _tempDuration = (double)_durationFrameCount / _durationTotalFrameCount; _currentState = KeyFramesStates.RunApplyValue; } break; case KeyFramesStates.RunBackwards: if (_durationFrameCount > _durationTotalFrameCount) { _currentState = KeyFramesStates.RunComplete; } else { _tempDuration = (double)(_durationTotalFrameCount - _durationFrameCount) / _durationTotalFrameCount; _currentState = KeyFramesStates.RunApplyValue; } break; case KeyFramesStates.RunApplyValue: _easedTime = _targetAnimation.Easing.Ease(_tempDuration); _durationFrameCount++; _lastInterpValue = Interpolator(_easedTime, _neutralValue); _targetObserver.OnNext(_lastInterpValue); _currentState = KeyFramesStates.DoRun; handled = true; break; case KeyFramesStates.RunComplete: if (_checkLoopAndRepeat) { _delayFrameCount = 0; _durationFrameCount = 0; if (_isLooping) { _currentState = KeyFramesStates.DoRun; } else if (_isRepeating) { if (_currentIteration >= _repeatCount) { _currentState = KeyFramesStates.Stop; } else { _currentState = KeyFramesStates.DoRun; } _currentIteration++; } if (_animationDirection == PlaybackDirection.Alternate || _animationDirection == PlaybackDirection.AlternateReverse) { _isReversed = !_isReversed; } break; } _currentState = KeyFramesStates.Stop; break; case KeyFramesStates.Stop: if (_fillMode == FillMode.Forward || _fillMode == FillMode.Both) { _targetControl.SetValue(_parent.Property, _lastInterpValue, BindingPriority.LocalValue); } _targetObserver.OnCompleted(); _onComplete?.Invoke(); Dispose(); handled = true; break; default: handled = true; break; } } }
/////////////////////////////////////////////////////////////////////////////// // Eventhandler // /////////////////////////////////////////////////////////////////////////////// #region EVENTS /////////////////////////////////////////////////////////////////////////////// // Eventhandler for UI, Menu, Buttons, Toolbars etc. // /////////////////////////////////////////////////////////////////////////////// #region WINDOWSEVENTHANDLER #endregion //WINDOWSEVENTHANDLER /////////////////////////////////////////////////////////////////////////////// // Eventhandler for Custom Defined Events // /////////////////////////////////////////////////////////////////////////////// #region CUSTOMEVENTHANDLER #endregion //CUSTOMEVENTHANDLER #endregion //EVENTS /////////////////////////////////////////////////////////////////////////////// // Methods and Eventhandling for Background tasks // /////////////////////////////////////////////////////////////////////////////// #region BACKGROUNDWORKER #endregion //BACKGROUNDWORKER /////////////////////////////////////////////////////////////////////////////// // Inherited methods // /////////////////////////////////////////////////////////////////////////////// #region OVERRIDES #endregion //OVERRIDES /////////////////////////////////////////////////////////////////////////////// // Methods for doing main class job // /////////////////////////////////////////////////////////////////////////////// #region PRIVATEMETHODS private void OpenClip(string filename) { try { this.filename = filename; // If no filename is specified, show file open dialog if (this.filename == string.Empty) { this.filename = GetClipFileName(); if (this.filename == string.Empty) return; } if (!System.IO.File.Exists(this.filename)) { return; } // Reset status variables this.currentState = PlayState.Stopped; this.currentVolume = VolumeFull; // Start playing the media file InitGraph(this.filename); } catch { CloseClip(); } }
/// <summary> /// Called when the playstate changes, except for the Error state (see OnError) /// </summary> /// <param name="player">The BackgroundAudioPlayer</param> /// <param name="track">The track playing at the time the playstate changed</param> /// <param name="playState">The new playstate of the player</param> /// <remarks> /// Play State changes cannot be cancelled. They are raised even if the application /// caused the state change itself, assuming the application has opted-in to the callback. /// /// Notable playstate events: /// (a) TrackEnded: invoked when the player has no current track. The agent can set the next track. /// (b) TrackReady: an audio track has been set and it is now ready for playack. /// /// Call NotifyComplete() only once, after the agent request has been completed, including async callbacks. /// </remarks> protected override void OnPlayStateChanged(BackgroundAudioPlayer player, AudioTrack track, PlayState playState) { switch (playState) { case PlayState.TrackEnded: player.Track = GetPreviousTrack(); break; case PlayState.TrackReady: player.Play(); break; case PlayState.Shutdown: // TODO: Handle the shutdown state here (e.g. save state) break; case PlayState.Unknown: break; case PlayState.Stopped: break; case PlayState.Paused: break; case PlayState.Playing: break; case PlayState.BufferingStarted: break; case PlayState.BufferingStopped: break; case PlayState.Rewinding: break; case PlayState.FastForwarding: break; } NotifyComplete(); }
///// <summary> ///// Wait for events to happen. This approach uses waiting on an event handle. ///// The nice thing about doing it this way is that you aren't in the windows message ///// loop, and don't have to worry about re-entrency or taking too long. Plus, being ///// in a class as we are, we don't have access to the message loop. ///// Alternately, you can receive your events as windows messages. See ///// IMediaEventEx.SetNotifyWindow. ///// </summary> ///// <remarks>We catch the EC_COMPLETE event in its default implementation, ///// that means it is only called when all running streams are finished. ///// MSDN says: ///// ///// EC_COMPLETE ///// All data from a particular stream has been rendered. ///// Parameters ///// lParam1 ///// (HRESULT) Status of the stream on completion. If no errors occurred during playback, the value is S_OK. ///// lParam2 ///// (IUnknown*) Zero, or a pointer to the renderer's IBaseFilter interface. ///// Default Action ///// By default, the filter graph manager does not forward this event to the application. However, after all the streams in the graph report EC_COMPLETE, the filter graph manager posts a separate EC_COMPLETE event to the application. ///// If the default action is disabled for this event, the application receives all of the EC_COMPLETE events from the renderers. ///// Remarks ///// A renderer filter sends this event when it receives an end-of-stream notice. (End-of-stream is signaled through the IPin::EndOfStream method.) The filter sends exactly one EC_COMPLETE event for each stream. The filter must process any pending samples before it sends the event. Stopping a renderer resets any end-of-stream state that was cached. ///// Filters set the lParam2 parameter to an IBaseFilter pointer. If the default action is enabled, the filter graph manager sets this parameter to zero. ///// </remarks> //private void EventWait() //{ // // Returned when GetEvent is called but there are no events // const int E_ABORT = unchecked((int)0x80004004); // int hr; // IntPtr p1, p2; // EventCode ec; // do // { // // Wait for an event // manualResetEvent.WaitOne(10, false); // // Avoid contention for m_State // //lock (this) // { // // If we are not shutting down // if (this.currentState != PlayState.Exiting&&this.mediaEvent!=null) // { // // Read the event // for ( // hr = this.mediaEvent.GetEvent(out ec, out p1, out p2, 0); // hr >= 0; // hr = this.mediaEvent.GetEvent(out ec, out p1, out p2, 0) // ) // { // // Write the event name to the debug window // //Console.WriteLine(ec.ToString()); // // Release any resources the message allocated // hr = this.mediaEvent.FreeEventParams(ec, p1, p2); // DsError.ThrowExceptionForHR(hr); // // If the clip is finished playing // if (ec == EventCode.Complete) // { // // Call Stop() to set state // Stop(); // // Throw event // if (StopPlay != null) // { // StopPlay(this); // } // //this.currentState = PlayState.Exiting; // break; // } // } // // If the error that exited the loop wasn't due to running out of events // if (hr != E_ABORT) // { // DsError.ThrowExceptionForHR(hr); // } // } // else // { // // We are shutting down // break; // } // } // } while (true);//this.currentState != PlayState.Exiting); //} private void CloseClip() { Stop(); // Free DirectShow interfaces CloseInterfaces(); // Clear file name to allow selection of new file with open dialog this.filename = string.Empty; // No current media state this.currentState = PlayState.None; }
private void StopClip() { int hr = 0; DsLong pos = new DsLong(0); if ((this.mediaControl == null) || (this.mediaSeeking == null)) return; // Stop and reset postion to beginning if ((this.currentState == PlayState.Paused) || (this.currentState == PlayState.Running)) { hr = this.mediaControl.Stop(); this.currentState = PlayState.Stopped; // Seek to the beginning hr = this.mediaSeeking.SetPositions(pos, AMSeekingSeekingFlags.AbsolutePositioning, null, AMSeekingSeekingFlags.NoPositioning); // Display the first frame to indicate the reset condition hr = this.mediaControl.Pause(); } }
public UserControlImageSurface() { InitializeComponent(); state = PlayState.Init; }
public void backPropagate() { PlayState ps = game.CurrentPlayer.PlayState; }
private void Cleanup() { if (graphBuilder == null) { return; } int hr; Log.Info("RTSPPlayer:cleanup DShow graph"); try { if (_mediaCtrl != null) { int counter = 0; FilterState state; hr = _mediaCtrl.Stop(); hr = _mediaCtrl.GetState(10, out state); while (state != FilterState.Stopped || GUIGraphicsContext.InVmr9Render) { Thread.Sleep(100); hr = _mediaCtrl.GetState(10, out state); counter++; if (counter >= 30) { if (state != FilterState.Stopped) { Log.Error("RTSPPlayer: graph still running"); } if (GUIGraphicsContext.InVmr9Render) { Log.Error("RTSPPlayer: in renderer"); } break; } } _mediaCtrl = null; } if (Vmr9 != null) { Vmr9.Enable(false); } if (mediaEvt != null) { hr = mediaEvt.SetNotifyWindow(IntPtr.Zero, WM_GRAPHNOTIFY, IntPtr.Zero); mediaEvt = null; } videoWin = graphBuilder as IVideoWindow; if (videoWin != null) { hr = videoWin.put_Visible(OABool.False); hr = videoWin.put_Owner(IntPtr.Zero); videoWin = null; } _mediaSeeking = null; mediaPos = null; basicAudio = null; basicVideo = null; videoWin = null; SubEngine.GetInstance().FreeSubtitles(); if (graphBuilder != null) { DirectShowUtil.RemoveFilters(graphBuilder); if (_rotEntry != null) { _rotEntry.SafeDispose(); _rotEntry = null; } DirectShowUtil.ReleaseComObject(graphBuilder); graphBuilder = null; } if (Vmr9 != null) { Vmr9.SafeDispose(); Vmr9 = null; } GUIGraphicsContext.form.Invalidate(true); _state = PlayState.Init; if (_mpegDemux != null) { Log.Info("cleanup mpegdemux"); while ((hr = DirectShowUtil.ReleaseComObject(_mpegDemux)) > 0) { ; } _mpegDemux = null; } if (_rtspSource != null) { Log.Info("cleanup _rtspSource"); while ((hr = DirectShowUtil.ReleaseComObject(_rtspSource)) > 0) { ; } _rtspSource = null; } if (_subtitleFilter != null) { while ((hr = DirectShowUtil.ReleaseComObject(_subtitleFilter)) > 0) { ; } _subtitleFilter = null; if (this.dvbSubRenderer != null) { this.dvbSubRenderer.SetPlayer(null); } this.dvbSubRenderer = null; } if (vobSub != null) { Log.Info("cleanup vobSub"); while ((hr = DirectShowUtil.ReleaseComObject(vobSub)) > 0) { ; } vobSub = null; } } catch (Exception ex) { Log.Error("RTSPPlayer: Exception while cleanuping DShow graph - {0} {1}", ex.Message, ex.StackTrace); } //switch back to directx windowed mode Log.Info("RTSPPlayer: Disabling DX9 exclusive mode"); GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SWITCH_FULL_WINDOWED, 0, 0, 0, 0, 0, null); GUIWindowManager.SendMessage(msg); }
private void PlayMovieInWindow(string filename) { int hr = 0; if (filename == string.Empty) { return; } this.graphBuilder = (IGraphBuilder) new FilterGraph(); // Have the graph builder construct its the appropriate graph automatically hr = this.graphBuilder.RenderFile(filename, null); DsError.ThrowExceptionForHR(hr); // QueryInterface for DirectShow interfaces this.mediaControl = (IMediaControl)this.graphBuilder; this.mediaEventEx = (IMediaEventEx)this.graphBuilder; this.mediaSeeking = (IMediaSeeking)this.graphBuilder; this.mediaPosition = (IMediaPosition)this.graphBuilder; // Query for video interfaces, which may not be relevant for audio files this.videoWindow = this.graphBuilder as IVideoWindow; this.basicVideo = this.graphBuilder as IBasicVideo; // Query for audio interfaces, which may not be relevant for video-only files this.basicAudio = this.graphBuilder as IBasicAudio; // Is this an audio-only file (no video component)? CheckVisibility(); // Have the graph signal event via window callbacks for performance hr = this.mediaEventEx.SetNotifyWindow(this.Handle, WMGraphNotify, IntPtr.Zero); DsError.ThrowExceptionForHR(hr); if (!this.isAudioOnly) { // Setup the video window hr = this.videoWindow.put_Owner(this.Handle); DsError.ThrowExceptionForHR(hr); hr = this.videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipSiblings | WindowStyle.ClipChildren); DsError.ThrowExceptionForHR(hr); hr = InitVideoWindow(1, 1); DsError.ThrowExceptionForHR(hr); GetFrameStepInterface(); } else { // Initialize the default player size and enable playback menu items hr = InitPlayerWindow(); DsError.ThrowExceptionForHR(hr); EnablePlaybackMenu(true, MediaType.Audio); } // Complete window initialization CheckSizeMenu(menuFileSizeNormal); this.isFullScreen = false; this.currentPlaybackRate = 1.0; UpdateMainTitle(); #if DEBUG rot = new DsROTEntry(this.graphBuilder); #endif this.Focus(); // Run the graph to play the media file hr = this.mediaControl.Run(); DsError.ThrowExceptionForHR(hr); this.currentState = PlayState.Running; }
public virtual void OnSetPlayState(PlayState newState) { }
public void Stop() { _state = PlayState.STOPPED; }
/// <summary> handling the very first start of dvd playback. </summary> private bool FirstPlayDvd(string file) { int hr; try { _pendingCmd = true; CloseDVDInterfaces(); string path = null; _currentFile = file; if (MediaPortal.Util.VirtualDirectory.IsImageFile(System.IO.Path.GetExtension(file))) { file = MediaPortal.Util.DaemonTools.GetVirtualDrive() + @"\VIDEO_TS\VIDEO_TS.IFO"; } // Cyberlink navigator needs E:\\VIDEO_TS formatted path with double \ path = file.Replace(@"\\", @"\").Replace(Path.GetFileName(file), "").Replace(@"\", @"\\"); if (!GetDVDInterfaces(path)) { logger.Error("DVDPlayer:Unable getinterfaces()"); CloseDVDInterfaces(); return(false); } if (_basicVideo != null) { _basicVideo.SetDefaultSourcePosition(); _basicVideo.SetDefaultDestinationPosition(); } /* hr = _mediaCtrl.Run(); * if (hr < 0 || hr > 1) * { * MediaPortal.Util.HResult hrdebug = new MediaPortal.Util.HResult(hr); * logger.Info(hrdebug.ToDXString()); * Log.Error("DVDPlayer:Unable to start playing() 0x:{0:X}", hr); * CloseDVDInterfaces(); * return false; * } */ DvdDiscSide side; int titles, numOfVolumes, volume; hr = _dvdInfo.GetDVDVolumeInfo(out numOfVolumes, out volume, out side, out titles); if (hr < 0) { logger.Error("DVDPlayer:Unable to get dvdvolumeinfo 0x{0:X}", hr); CloseDVDInterfaces(); return(false); // can't read disc } else { if (titles <= 0) { logger.Error("DVDPlayer:DVD does not contain any titles? {0}", titles, 1); //return false; } } hr = _dvdCtrl.SelectVideoModePreference(_videoPref); DvdVideoAttributes videoAttr; hr = _dvdInfo.GetCurrentVideoAttributes(out videoAttr); _videoWidth = videoAttr.sourceResolutionX; _videoHeight = videoAttr.sourceResolutionY; _state = PlayState.Playing; _pendingCmd = false; logger.Info("DVDPlayer:Started playing()"); if (_currentFile == string.Empty) { for (int i = 0; i <= 26; ++i) { string dvd = String.Format("{0}:", (char)('A' + i)); if (MediaPortal.Util.Utils.IsDVD(dvd)) { _currentFile = String.Format(@"{0}:\VIDEO_TS\VIDEO_TS.IFO", (char)('A' + i)); if (File.Exists(_currentFile)) { break; } } } } return(true); } catch (Exception ex) { logger.ErrorException("DVDPlayer:Could not start DVD:{0} {1} {2}", ex); CloseDVDInterfaces(); return(false); } }
public void Replay() { tickcount = 0; if (image != null) state = PlayState.Running; }
protected virtual void UpdateStatus() { var transport = MediaTransport; PlayState state = PlayState.Undefined; if (transport != null) { state = transport.PlayState; //changed this to get the "Name" property instead. That makes it compatable with DVD playback as well. string title = null; try { title = MediaExperience.MediaMetadata["Name"] as string; //Logger.ReportVerbose("Full title: " + title); title = title.ToLower(); //lowercase it for comparison } catch (Exception e) { Logger.ReportException("Failed to get name on current media item! Trying Title...", e); try { title = MediaExperience.MediaMetadata["Title"] as string; //Logger.ReportVerbose("Full title: " + title); title = title.ToLower(); } catch (Exception ex) { Logger.ReportException("That didn't work either. Giving up...", ex); } } if (title != this.title) { duration = null; //changed items we were playing } long position = transport.Position.Ticks; try { //only track position for a reasonable portion of the video if (duration == null) //only need to do this once per item { //first try mediacenter duration = (TimeSpan.Parse((string)MediaExperience.MediaMetadata["Duration"])).Ticks; if (duration == 0) //not there - see if we have it from meta { duration = (TimeSpan.FromMinutes(metaDuration)).Ticks; } } //Logger.ReportVerbose("position "+position+ " duration "+duration); if (duration > 0) { decimal pctIn = Decimal.Divide(position, duration.Value) * 100; //Logger.ReportVerbose("pctIn: " + pctIn + " duration: " + duration); if (pctIn < Config.Instance.MinResumePct || pctIn > Config.Instance.MaxResumePct) { position = 0; //don't track in very begginning or very end } } } catch { } // couldn't get duration - no biggie just don't blow chow if (title != null && progressHandler != null && (this.title != title || this.position != position) && (duration == 0 || (duration / TimeSpan.TicksPerMinute) >= Config.Instance.MinResumeDuration)) { //Logger.ReportVerbose("progressHandler was called with : position =" + position.ToString() + " title :" + title); progressHandler(this, new PlaybackStateEventArgs() { Position = position, Title = title }); this.title = title; this.position = position; } } if (state != PlayState) { Logger.ReportVerbose("Playstate changed to " + state + " for " + title); PlayState = state; Logger.ReportVerbose("Invoking Playstate changed events..."); Microsoft.MediaCenter.UI.Application.DeferredInvoke(_ => PlayStateChanged()); Logger.ReportVerbose("Setting now playing status..."); Application.CurrentInstance.ShowNowPlaying = ( (state == Microsoft.MediaCenter.PlayState.Playing) || (state == Microsoft.MediaCenter.PlayState.Paused)); Logger.ReportVerbose("Updating Resume status..."); Application.CurrentInstance.CurrentItem.UpdateResume(); if (state == Microsoft.MediaCenter.PlayState.Finished || state == Microsoft.MediaCenter.PlayState.Stopped || state == Microsoft.MediaCenter.PlayState.Undefined) { Logger.ReportVerbose("Stopped so detaching..."); Detach(); //we don't want to continue to get updates if play something outside MB //we're done - call post-processor Logger.ReportVerbose("Calling post play..."); Application.CurrentInstance.RunPostPlayProcesses(); Logger.ReportVerbose("Finished all playstate events"); } } if (IsWindows7) { if (lastWasDVD && !returnedToApp && state == PlayState.Stopped) { Logger.ReportVerbose("Ensuring MB is front-most app"); Microsoft.MediaCenter.UI.Application.DeferredInvoke(_ => { AddInHost.Current.ApplicationContext.ReturnToApplication(); }); returnedToApp = true; } } //Logger.ReportVerbose("Out of updatestatus"); }
/// <summary> /// Helps deal with potential conflicts between the eventing thread /// and client calls to Cancel() /// </summary> /// <param name="newState">State to change to</param> private void ChangeState(PlayState newState) { lock (this) { //if (m_State == PlayState..GraphStarted) //{ this.currentState = newState; //} } }
private void SeekSlider_DragStarted(object sender, EventArgs e) { _playStateBeforeDragging = PlayState; _isDragging = true; Pause(); }
/* * Media Related methods */ /// <summary> /// Pauses / unpauses clip according to state. /// </summary> public void Pause() { if (this.mediaControl == null) return; // Toggle play/pause behavior if ((this.currentState == PlayState.Paused) || (this.currentState == PlayState.Stopped)) { if (this.mediaControl.Run() >= 0) this.currentState = PlayState.Running; } else { if (this.mediaControl.Pause() >= 0) this.currentState = PlayState.Paused; } }
private void UpdateDiscordPresence(PlayState playerGetPlayState) { var metaDataDict = GenerateMetaDataDictionary(); // Discord allows only strings with a min length of 2 or the update fails // so add some exotic space (Mongolian vovel seperator) to the string if it is smaller // Discord also disallows strings bigger than 128bytes so handle that as well string padString(string input) { if (!string.IsNullOrEmpty(input)) { if (input.Length < 2) { return(input + "\u180E"); } if (Encoding.UTF8.GetBytes(input).Length > 128) { byte[] buffer = new byte[128]; char[] inputChars = input.ToCharArray(); Encoding.UTF8.GetEncoder().Convert( chars: inputChars, charIndex: 0, charCount: inputChars.Length, bytes: buffer, byteIndex: 0, byteCount: buffer.Length, flush: false, charsUsed: out _, bytesUsed: out int bytesUsed, completed: out _); return(Encoding.UTF8.GetString(buffer, 0, bytesUsed)); } } return(input); } void SetImage(string name) { if (_settings.TextOnly) { _discordPresence.Assets.LargeImageKey = null; _discordPresence.Assets.LargeImageText = null; _discordPresence.Assets.SmallImageKey = null; _discordPresence.Assets.SmallImageText = null; return; } _discordPresence.Assets.LargeImageKey = "logo"; _discordPresence.Assets.LargeImageText = padString(_layoutHandler.Render(_settings.LargeImageText, metaDataDict, _settings.Seperator)); _discordPresence.Assets.SmallImageKey = padString(name); _discordPresence.Assets.SmallImageText = padString(_layoutHandler.Render(_settings.SmallImageText, metaDataDict, _settings.Seperator));; } _discordPresence.State = padString(_layoutHandler.Render(_settings.PresenceState, metaDataDict, _settings.Seperator)); var t = DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)); if (_settings.ShowRemainingTime) { // show remaining time // subtract current track position from total duration for position seeking var totalRemainingDuration = _mbApiInterface.NowPlaying_GetDuration() - _mbApiInterface.Player_GetPosition(); _discordPresence.Timestamps.EndUnixMilliseconds = (ulong)(Math.Round(t.TotalSeconds) + Math.Round(totalRemainingDuration / 1000.0)); } else { // show elapsed time _discordPresence.Timestamps.StartUnixMilliseconds = (ulong)(Math.Round(t.TotalSeconds) - Math.Round(_mbApiInterface.Player_GetPosition() / 1000.0)); } switch (playerGetPlayState) { case PlayState.Playing: SetImage("play"); break; case PlayState.Stopped: SetImage("stop"); _discordPresence.Timestamps.Start = null; _discordPresence.Timestamps.End = null; break; case PlayState.Paused: SetImage("pause"); _discordPresence.Timestamps.Start = null; _discordPresence.Timestamps.End = null; break; case PlayState.Undefined: case PlayState.Loading: break; } _discordPresence.Details = padString(_layoutHandler.Render(_settings.PresenceDetails, metaDataDict, _settings.Seperator)); var trackcnt = -1; var trackno = -1; try { trackcnt = int.Parse(_layoutHandler.Render(_settings.PresenceTrackCnt, metaDataDict, _settings.Seperator)); trackno = int.Parse(_layoutHandler.Render(_settings.PresenceTrackNo, metaDataDict, _settings.Seperator)); } catch (Exception) { // ignored } if (trackcnt < trackno || trackcnt <= 0 || trackno <= 0) { _discordPresence.Party = null; } else { _discordPresence.Party = new Party { ID = "aaaa", Max = trackcnt, Size = trackno }; } if (!_settings.UpdatePresenceWhenStopped && (playerGetPlayState == PlayState.Paused || playerGetPlayState == PlayState.Stopped)) { _discordClient.ClearPresence(); } else { _discordClient.SetPresence(_discordPresence); } }
private void timerImg_Tick(object sender, EventArgs e) { if (state == PlayState.Running) { tickcount++; if (tickcount > duration) { state = PlayState.Stopped; if (PlayFinishedEvent != null) { PlayFinishedEvent(this, EventArgs.Empty); } } } }
public void TogglePlayStateEventHandler(object?sender, EventArgs eventArgs) { _playState = _playState != PlayState.Running ? PlayState.Running : PlayState.Stopped; }
private void DoPlayStatusChanged(IMonitorSystemContext context, string vsName, VideoSourceState vsStatus, PlayState playStatus) { if (mVSConfig.Name.Equals(vsName)) { IFileVideoSource vs = context.VideoSourceManager.GetVideoSource(vsName) as IFileVideoSource; switch (playStatus) { case PlayState.Open: if (vs != null) { InitPlayProgress((int)vs.TotalFrame); } button_open.Text = "关闭"; button_play.Text = "播放"; button_play.Enabled = true; button_playFrame.Enabled = true; button_getFrame.Enabled = true; break; case PlayState.Play: button_play.Text = "暂停"; break; case PlayState.Stop: button_play.Text = "播放"; break; case PlayState.Close: button_open.Text = "打开"; button_play.Text = "播放"; button_play.Enabled = false; button_playFrame.Enabled = false; button_getFrame.Enabled = false; label_fileName.Text = string.Format("{0}未打开文件", Desc); label_totalTime.Text = "0:00:00"; label_curTime.Text = "0:00:00"; progressBar_play.Value = 0; break; } if (OnPlayStatusChanged != null) { OnPlayStatusChanged(context, vsName, vsStatus, playStatus); } } }
public override bool Play(string strFile) { updateTimer = DateTime.Now; m_speedRate = 10000; m_bVisible = false; m_iVolume = 100; _state = PlayState.Init; m_strCurrentFile = strFile; m_bFullScreen = true; m_ar = GUIGraphicsContext.ARType; VideoRendererStatistics.VideoState = VideoRendererStatistics.State.VideoPresent; _updateNeeded = true; Log.Info("RTSPPlayer:play {0}", strFile); //lock ( typeof(VideoPlayerVMR7) ) { CloseInterfaces(); m_bStarted = false; if (!GetInterfaces()) { m_strCurrentFile = ""; CloseInterfaces(); return(false); } int hr = mediaEvt.SetNotifyWindow(GUIGraphicsContext.ActiveForm, WM_GRAPHNOTIFY, IntPtr.Zero); if (hr < 0) { Error.SetError("Unable to play movie", "Can not set notifications"); m_strCurrentFile = ""; CloseInterfaces(); return(false); } DirectShowUtil.SetARMode(graphBuilder, AspectRatioMode.Stretched); _rotEntry = new DsROTEntry((IFilterGraph)graphBuilder); // DsUtils.DumpFilters(graphBuilder); hr = _mediaCtrl.Run(); if (hr < 0) { Error.SetError("Unable to play movie", "Unable to start movie"); m_strCurrentFile = ""; CloseInterfaces(); return(false); } GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_PLAYBACK_STARTED, 0, 0, 0, 0, 0, null); msg.Label = strFile; GUIWindowManager.SendThreadMessage(msg); _state = PlayState.Playing; //Brutus GUIGraphicsContext.IsFullScreenVideo=true; m_iPositionX = GUIGraphicsContext.VideoWindow.X; m_iPositionY = GUIGraphicsContext.VideoWindow.Y; m_iWidth = GUIGraphicsContext.VideoWindow.Width; m_iHeight = GUIGraphicsContext.VideoWindow.Height; m_ar = GUIGraphicsContext.ARType; _updateNeeded = true; SetVideoWindow(); mediaPos.get_Duration(out _duration); Log.Info("RTSPPlayer:Duration:{0}", _duration); if (_mediaType == g_Player.MediaType.TV) { //if (_duration < 1) _duration = 1; //SeekAbsolute(_duration - 1); } else { //SeekAbsolute(0); } OnInitialized(); } // Wait for a while to wait VMR9 to get ready. // Implemented due to problems starting to play before VMR9 was ready resulting in black screen. Thread.Sleep(200); return(true); }
public void Stop() { state = PlayState.Stopped; }
protected override void OnPlayStateChanged(BackgroundAudioPlayer player, AudioTrack track, PlayState playState) { bool flag = true; try { switch (playState) { case PlayState.TrackReady: if (player.PlayerState != PlayState.Playing) { flag = false; AudioTrackHelper.PlayCurrentTrack(player, (Action <bool>)(res => this.NotifyComplete()), false); break; } break; case PlayState.TrackEnded: PlaybackSettings settings = PlaylistManager.ReadPlaybackSettings(false); if (settings.Repeat) { player.Stop(); player.Position = TimeSpan.FromSeconds(0.0); flag = false; AudioTrackHelper.PlayCurrentTrack(player, (Action <bool>)(res => this.NotifyComplete()), false); break; } bool startedNewCycle; AudioTrack nextTrack = this.GetNextTrack(player, out startedNewCycle, settings); if (nextTrack != null) { if (!startedNewCycle) { player.Track = nextTrack; AudioTrackHelper.PlayCurrentTrack(player, (Action <bool>)(res => this.NotifyComplete()), false); flag = false; break; } this.NotifyComplete(); break; } break; } AudioTrackHelper.BroadcastTrackIfNeeded(player, null, null, false, false); if (!flag) { return; } this.NotifyComplete(); } catch { this.NotifyComplete(); } }