/** * Constructor */ public VideoView() { mMediaElement = new MediaElement(); mView = mMediaElement; /** * the delegates that respond to the widget's events */ // MAW_VIDEO_VIEW_STATE_FINISHED mMediaElement.MediaEnded += new RoutedEventHandler( delegate(object from, RoutedEventArgs args) { // post the event to MoSync runtime Memory eventData = new Memory(8); const int MAWidgetEventData_eventType = 0; const int MAWidgetEventData_widgetHandle = 4; eventData.WriteInt32(MAWidgetEventData_eventType, MoSync.Constants.MAW_VIDEO_VIEW_STATE_FINISHED); eventData.WriteInt32(MAWidgetEventData_widgetHandle, mHandle); mRuntime.PostCustomEvent(MoSync.Constants.EVENT_TYPE_WIDGET, eventData); } ); // end of mMediaElement.MediaEnded // MAW_VIDEO_VIEW_STATE_SOURCE_READY mMediaElement.MediaOpened += new RoutedEventHandler( delegate(object from, RoutedEventArgs args) { // post the event to MoSync runtime Memory eventData = new Memory(8); const int MAWidgetEventData_eventType = 0; const int MAWidgetEventData_widgetHandle = 4; eventData.WriteInt32(MAWidgetEventData_eventType, MoSync.Constants.MAW_VIDEO_VIEW_STATE_SOURCE_READY); eventData.WriteInt32(MAWidgetEventData_widgetHandle, mHandle); mRuntime.PostCustomEvent(MoSync.Constants.EVENT_TYPE_WIDGET, eventData); } ); // end of mMediaElement.MediaOpened // MAW_VIDEO_VIEW_STATE_INTERRUPTED mMediaElement.MediaFailed += new EventHandler<ExceptionRoutedEventArgs>( delegate(object from, ExceptionRoutedEventArgs args) { // post the event to MoSync runtime Memory eventData = new Memory(8); const int MAWidgetEventData_eventType = 0; const int MAWidgetEventData_widgetHandle = 4; eventData.WriteInt32(MAWidgetEventData_eventType, MoSync.Constants.MAW_VIDEO_VIEW_STATE_INTERRUPTED); eventData.WriteInt32(MAWidgetEventData_widgetHandle, mHandle); mRuntime.PostCustomEvent(MoSync.Constants.EVENT_TYPE_WIDGET, eventData); } ); // end of mMediaElement.MediaFailed }
/// <summary> /// Creates a new instance of VpaidVideoAdPlayer. /// </summary> /// <param name="skippableOffset">The position in the ad at which the ad can be skipped. If null, the ad cannot be skipped.</param> /// <param name="maxDuration">The max duration of the ad. If not specified, the length of the video is assumed.</param> /// <param name="clickThru">The Uri to navigate to when the ad is clicked or tapped. Can be null of no action should take place.</param> public VpaidVideoAdPlayer(FlexibleOffset skippableOffset, TimeSpan? maxDuration, Uri clickThru) { IsHitTestVisible = false; mediaElement = new MediaElement(); Background = new SolidColorBrush(Colors.Black); #if !WINDOWS80 Opacity = 0.01; // HACK: Win8.1 won't load the video if opacity = 0 #else Opacity = 0; #endif State = AdState.None; AdLinear = true; SkippableOffset = skippableOffset; MaxDuration = maxDuration; this.NavigateUri = clickThru; }
/// <inheritdoc /> public void Render(MediaBlock mediaBlock, TimeSpan clockPosition) { if (mediaBlock is VideoBlock == false) { return; } var block = (VideoBlock)mediaBlock; if (IsRenderingInProgress.Value) { if (MediaCore?.State.IsPlaying ?? false) { this.LogDebug(Aspects.VideoRenderer, $"{nameof(VideoRenderer)} frame skipped at {mediaBlock.StartTime}"); } return; } // Flag the start of a rendering cycle IsRenderingInProgress.Value = true; // Send the packets to the CC renderer MediaElement?.CaptionsView?.SendPackets(block, MediaCore); // Create an action that holds GUI thread actions var foregroundAction = new Action(() => { MediaElement?.CaptionsView?.Render(MediaElement.ClosedCaptionsChannel, clockPosition); ApplyLayoutTransforms(block); }); var canStartForegroundTask = MediaElement.VideoView.ElementDispatcher != MediaElement.Dispatcher; var foregroundTask = canStartForegroundTask ? MediaElement.Dispatcher.InvokeAsync(foregroundAction) : null; // Ensure the target bitmap can be loaded MediaElement?.VideoView?.InvokeAsync(DispatcherPriority.Render, () => { if (block.IsDisposed) { IsRenderingInProgress.Value = false; return; } // Run the foreground action if we could not start it in parallel. if (foregroundTask == null) { try { foregroundAction(); } catch (Exception ex) { this.LogError(Aspects.VideoRenderer, $"{nameof(VideoRenderer)}.{nameof(Render)} layout/CC failed.", ex); } } try { var frameRateLimit = MediaElement.RendererOptions.VideoRefreshRateLimit; var isRenderTime = frameRateLimit <= 0 || !RenderStopwatch.IsRunning || RenderStopwatch.ElapsedMilliseconds >= 1000d / frameRateLimit; if (!isRenderTime) { return; } RenderStopwatch.Restart(); // Render the bitmap data var bitmapData = LockTargetBitmap(block); if (bitmapData == null) { return; } LoadTargetBitmapBuffer(bitmapData, block); MediaElement.RaiseRenderingVideoEvent(block, bitmapData, clockPosition); RenderTargetBitmap(bitmapData); } catch (Exception ex) { this.LogError(Aspects.VideoRenderer, $"{nameof(VideoRenderer)}.{nameof(Render)} bitmap failed.", ex); } finally { if (foregroundTask != null) { try { if (foregroundTask.Wait(CaptionsLayoutTimeout) != DispatcherOperationStatus.Completed) { this.LogError(Aspects.VideoRenderer, $"{nameof(VideoRenderer)}.{nameof(Render)} layout/CC timed out."); } } catch (Exception ex) { this.LogError(Aspects.VideoRenderer, $"{nameof(VideoRenderer)}.{nameof(Render)} layout/CC failed.", ex); } } // Always reset the rendering state IsRenderingInProgress.Value = false; } }); }
//private static StorageFolder _soundFilesFolder = null; //public static StorageFolder SoundFilesFolder //{ // get { return _soundFilesFolder; } // set { _soundFilesFolder = value; } //} //private StorageFile _soundFile; //private MediaElement _soundMediaElement; //private IRandomAccessStream _stream; public MusicalNote(Piano.MusicalNoteNames note) { _soundMediaElement = new MediaElement(); _soundMediaElement.AutoPlay = true; LoadSoundFileTask(note.ToString()); }
public MainPageViewModel() { MediaElement = new MediaElement(); ClickCommand = new DelegateCommand(OnClick); PlayCommand = new DelegateCommand(PlayExecute); }
private void ApplyEvent(IEvent ev) { if (ev is ICrudEvent crudEvent) { var entity = (crudEvent.GetEntityType(), crudEvent.Id); if (crudEvent is IDeleteEvent) { ClearIncomingReferences(entity); ClearOutgoingReferences(entity); } else if (crudEvent is IUpdateEvent) { ClearOutgoingReferences(entity); } } switch (ev) { case ExhibitCreated e: var newExhibit = new Exhibit(e.Properties) { Id = e.Id, UserId = e.UserId, Timestamp = e.Timestamp }; _db.GetCollection <Exhibit>(ResourceType.Exhibit.Name).InsertOne(newExhibit); break; case ExhibitUpdated e: var originalExhibit = _db.GetCollection <Exhibit>(ResourceType.Exhibit.Name).AsQueryable().First(x => x.Id == e.Id); var updatedExhibit = new Exhibit(e.Properties) { Id = e.Id, UserId = originalExhibit.UserId, Timestamp = e.Timestamp }; updatedExhibit.Referencers.AddRange(originalExhibit.Referencers); _db.GetCollection <Exhibit>(ResourceType.Exhibit.Name).ReplaceOne(x => x.Id == e.Id, updatedExhibit); break; case ExhibitDeleted e: MarkDeleted <Exhibit>(ResourceType.Exhibit, e.Id); break; case ExhibitPageCreated3 e: var newPage = new ExhibitPage(e.Properties) { Id = e.Id, UserId = e.UserId, Timestamp = e.Timestamp }; _db.GetCollection <ExhibitPage>(ResourceType.ExhibitPage.Name).InsertOne(newPage); break; case ExhibitPageUpdated3 e: var originalPage = _db.GetCollection <ExhibitPage>(ResourceType.ExhibitPage.Name).AsQueryable().First(x => x.Id == e.Id); var updatedPage = new ExhibitPage(e.Properties) { Id = e.Id, UserId = originalPage.UserId, Timestamp = e.Timestamp }; updatedPage.Referencers.AddRange(originalPage.Referencers); _db.GetCollection <ExhibitPage>(ResourceType.ExhibitPage.Name).ReplaceOne(x => x.Id == e.Id, updatedPage); break; case ExhibitPageDeleted2 e: MarkDeleted <ExhibitPage>(ResourceType.ExhibitPage, e.Id); break; case RouteCreated e: var newRoute = new Route(e.Properties) { Id = e.Id, UserId = e.UserId, Timestamp = e.Timestamp }; _db.GetCollection <Route>(ResourceType.Route.Name).InsertOne(newRoute); break; case RouteUpdated e: var originalRoute = _db.GetCollection <Route>(ResourceType.Route.Name).AsQueryable().First(x => x.Id == e.Id); var updatedRoute = new Route(e.Properties) { Id = e.Id, UserId = originalRoute.UserId, Timestamp = e.Timestamp }; updatedRoute.Referencers.AddRange(originalRoute.Referencers); _db.GetCollection <Route>(ResourceType.Route.Name).ReplaceOne(r => r.Id == e.Id, updatedRoute); break; case RouteDeleted e: MarkDeleted <Route>(ResourceType.Route, e.Id); break; case MediaCreated e: var newMedia = new MediaElement(e.Properties) { Id = e.Id, UserId = e.UserId, Timestamp = e.Timestamp }; _db.GetCollection <MediaElement>(ResourceType.Media.Name).InsertOne(newMedia); break; case MediaUpdate e: var originalMedia = _db.GetCollection <MediaElement>(ResourceType.Media.Name).AsQueryable().First(x => x.Id == e.Id); var updatedMedia = new MediaElement(e.Properties) { Id = e.Id, UserId = originalMedia.UserId, Timestamp = e.Timestamp }; updatedMedia.Referencers.AddRange(originalMedia.Referencers); updatedMedia.File = originalMedia.File; _db.GetCollection <MediaElement>(ResourceType.Media.Name).ReplaceOne(m => m.Id == e.Id, updatedMedia); break; case MediaDeleted e: MarkDeleted <MediaElement>(ResourceType.Media, e.Id); break; case MediaFileUpdated e: var fileDocBson = e.ToBsonDocument(); fileDocBson.Remove("_id"); var bsonDoc = new BsonDocument("$set", fileDocBson); _db.GetCollection <MediaElement>(ResourceType.Media.Name).UpdateOne(x => x.Id == e.Id, bsonDoc); break; case TagCreated e: var newTag = new Tag(e.Properties) { Id = e.Id, UserId = e.UserId, Timestamp = e.Timestamp, }; _db.GetCollection <Tag>(ResourceType.Tag.Name).InsertOne(newTag); break; case TagUpdated e: var originalTag = _db.GetCollection <Tag>(ResourceType.Tag.Name).AsQueryable().First(x => x.Id == e.Id); var updatedTag = new Tag(e.Properties) { Id = e.Id, UserId = originalTag.UserId, Timestamp = e.Timestamp, }; updatedTag.Referencers.AddRange(originalTag.Referencers); _db.GetCollection <Tag>(ResourceType.Tag.Name).ReplaceOne(x => x.Id == e.Id, updatedTag); break; case TagDeleted e: MarkDeleted <Tag>(ResourceType.Tag, e.Id); break; case ScoreAdded e: var newScoreRecord = new ScoreRecord { Id = e.Id, UserId = e.UserId, Score = e.Score, Timestamp = e.Timestamp }; _db.GetCollection <ScoreRecord>(ResourceType.ScoreRecord.Name).InsertOne(newScoreRecord); break; } if (ev is ICreateEvent createEvent) { AddReferences((createEvent.GetEntityType(), createEvent.Id), createEvent.GetReferences()); } else if (ev is IUpdateEvent updateEvent) { AddReferences((updateEvent.GetEntityType(), updateEvent.Id), updateEvent.GetReferences()); } }
/// <summary> /// Fired when we should load the content. /// </summary> /// <param name="source"></param> public void OnPrepareContent() { // Run the rest on a background thread. Task.Run(async() => { var gifUrl = GetRedGifUrl(_mBase.Source.Url); if (!string.IsNullOrWhiteSpace(gifUrl)) { gifUrl = await GetRedGifUrlFromWatchUrl(gifUrl); } else { // Try to get the imgur url gifUrl = GetImgurUrl(_mBase.Source.Url); // If that failed try to get a url from GfyCat if (gifUrl.Equals(string.Empty)) { // We have to get it from gfycat gifUrl = await GetGfyCatGifUrl(GetGfyCatApiUrl(_mBase.Source.Url)); } } // Since some of this can be costly, delay the work load until we aren't animating. await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => { // If we didn't get anything something went wrong. if (string.IsNullOrWhiteSpace(gifUrl)) { _mBase.FireOnFallbackToBrowser(); TelemetryManager.ReportUnexpectedEvent(this, "FailedToShowGifAfterConfirm"); return; } lock (this) { // Make sure we aren't destroyed. if (_mBase.IsDestroyed) { return; } // Create the media element _mGifVideo = new MediaElement { HorizontalAlignment = HorizontalAlignment.Stretch }; _mGifVideo.Tapped += OnVideoTapped; _mGifVideo.CurrentStateChanged += OnVideoCurrentStateChanged; _mGifVideo.IsLooping = true; // Set the source _mGifVideo.Source = new Uri(gifUrl, UriKind.Absolute); _mGifVideo.Play(); // Add the video to the root ui_contentRoot.Children.Add(_mGifVideo); } }); }); }
public void AddToMediaElements(MediaElement mediaElement) { base.AddObject("MediaElements", mediaElement); }
private void Stop_Click(object sender, RoutedEventArgs e) { MediaElement.Stop(); }
public MediaElementAudioSourceNode CreateMediaElementSource(MediaElement mediaElement) { return default(MediaElementAudioSourceNode); }
public CompileCompletedEventArgs(MediaElement me) { m_element = me; }
public static MediaElement Compile(string stringToParse) { MediaElement element = new MediaElement(); IParsable parser = new FlMMLStyleParser(); element.Volume = 1; element.SetSource(parser.Parse(stringToParse)); return element; }
private void Teardown() { this.Navigated -= AdPlayer_Navigated; this.SizeChanged -= AdPlayer_SizeChanged; timer.Tick -= timer_Tick; if (timer.IsEnabled) timer.Stop(); timer = null; mediaElement.MediaOpened -= MediaElement_MediaOpened; mediaElement.MediaFailed -= MediaElement_MediaFailed; mediaElement.MediaEnded -= MediaElement_MediaEnded; mediaElement.CurrentStateChanged -= MediaElement_CurrentStateChanged; #if !HACK_MARKERREACHED mediaElement.MarkerReached -= MediaElement_MarkerReached; #endif // cancel any active tasks and remove them from the dictionary foreach (var task in stateChangedTasks) { task.Value.TrySetCanceled(); } stateChangedTasks.Clear(); OnTeardown(); this.Content = null; mediaElement = null; Opacity = 0; }
protected override void OnMediaEnded(MediaElement medieElement, int screen) { PlayOnRandomScreen(); }
public void RepeatSongs(MediaElement m) { //m.IsLooping = true; m.Position = TimeSpan.Zero; m.Play(); }
public MediaElementInteraction GetWatchInteraction([FromUri] Guid?mediaElementGuid = null, [FromUri] Guid?personGuid = null, Guid?personAliasGuid = null) { var rockContext = Service.Context as RockContext; var personService = new PersonService(rockContext); var personAliasService = new PersonAliasService(rockContext); var interactionService = new InteractionService(rockContext); int?personAliasId; // Get the person alias to associate with the interaction in // order of provided Person.Guid, then PersonAlias.Guid, then // the logged in Person. if (personGuid.HasValue) { personAliasId = personAliasService.GetPrimaryAliasId(personGuid.Value); } else if (personAliasGuid.HasValue) { personAliasId = personAliasService.GetId(personAliasGuid.Value); } else { personAliasId = GetPersonAliasId(rockContext); } // Verify we have a person alias, otherwise bail out. if (!personAliasId.HasValue) { var errorResponse = Request.CreateErrorResponse(HttpStatusCode.BadRequest, $"The personAliasId could not be determined."); throw new HttpResponseException(errorResponse); } MediaElement mediaElement = null; // In the future we might make MediaElementGuid optional so // perform the check this way rather than making it required // in the parameter list. if (mediaElementGuid.HasValue) { mediaElement = new MediaElementService(rockContext).GetNoTracking(mediaElementGuid.Value); } // Ensure we have our required MediaElement. if (mediaElement == null) { var errorResponse = Request.CreateErrorResponse(HttpStatusCode.BadRequest, $"The MediaElement could not be found."); throw new HttpResponseException(errorResponse); } // Get (or create) the component. var interactionChannelId = InteractionChannelCache.Get(SystemGuid.InteractionChannel.MEDIA_EVENTS).Id; var interactionComponentId = InteractionComponentCache.GetComponentIdByChannelIdAndEntityId(interactionChannelId, mediaElement.Id, mediaElement.Name); Interaction interaction = interactionService.Queryable() .AsNoTracking() .Include(a => a.PersonAlias) .Where(a => a.InteractionComponentId == interactionComponentId) .Where(a => a.PersonAliasId == personAliasId || a.PersonAlias.Person.Aliases.Any(b => b.Id == personAliasId)) .OrderByDescending(a => a.InteractionEndDateTime) .ThenByDescending(a => a.InteractionDateTime) .FirstOrDefault(); if (interaction == null) { var errorResponse = Request.CreateErrorResponse(HttpStatusCode.NotFound, $"The Interaction could not be found."); throw new HttpResponseException(errorResponse); } var data = interaction.InteractionData.FromJsonOrNull <MediaWatchedInteractionData>(); return(new MediaElementInteraction { InteractionGuid = interaction.Guid, MediaElementGuid = mediaElement.Guid, PersonGuid = interaction.PersonAlias.Person?.Guid, PersonAliasGuid = interaction.PersonAlias.Guid, RelatedEntityTypeId = interaction.RelatedEntityTypeId, RelatedEntityId = interaction.RelatedEntityId, WatchMap = data?.WatchMap ?? string.Empty }); }
/// <summary> /// Handles global FFmpeg library messages /// </summary> /// <param name="message">The message.</param> public void HandleFFmpegLogMessage(MediaLogMessage message) { MediaElement.RaiseFFmpegMessageLogged(typeof(MediaElement), message); }
public static void SetVideo(this IPreviewFrame previewFrame, Action onCompleted, Action onFailed, IObservable <double> volume) { Grid holder = previewFrame.Holder; if (HasChild <MediaElement>(holder)) { // There is already a video in here. RemoveImage(holder); return; } // Close any video that was there before. RemoveVideo(holder); // Add on a new video var mediaElement = new MediaElement { Stretch = Stretch.Fill, Opacity = 0 }; var viewModel = (PreviewWindowViewModel)previewFrame.Holder.DataContext; mediaElement.SetBinding(MediaElement.SourceProperty, nameof(viewModel.PreviewFilePath)); mediaElement.LoadedBehavior = MediaState.Manual; mediaElement.ScrubbingEnabled = true; mediaElement.MediaOpened += (sender, args) => { if (mediaElement.NaturalDuration.HasTimeSpan) { viewModel.PreviewVideoDuration = mediaElement.NaturalDuration.TimeSpan; } else { viewModel.PreviewVideoDuration = TimeSpan.Zero; } // Video starts out black so we want to hold it at the start until it displays fully. mediaElement.Pause(); DispatchUtilities.BeginInvoke(() => { OnVideoPlaying(holder); mediaElement.Play(); }); }; mediaElement.MediaFailed += (sender, args) => { onFailed(); }; mediaElement.MediaEnded += (sender, args) => { onCompleted(); }; volume.Subscribe(v => { mediaElement.Volume = v; }); mediaElement.Play(); holder.Children.Add(mediaElement); }
public CharacterCreationPage(Window title, MediaElement bgM) { main = title; music = bgM; InitializeComponent(); }
/// <summary> /// Like OnNavigatedTo(), but runs after the whole UI has already been prepared. /// Place any loading code here that requires the UI to be completely loaded. /// </summary> private async void page_Loaded(object sender, RoutedEventArgs e) { // Initialize the controller if necessary if (AudioController.Default.Status == AudioControllerStatus.NotReady) { DependencyObject rootGrid = Windows.UI.Xaml.Media.VisualTreeHelper.GetChild(Window.Current.Content, 0); MediaElement rootMediaElement = (MediaElement)Windows.UI.Xaml.Media.VisualTreeHelper.GetChild(rootGrid, 0); AudioController.Default.Ready(rootMediaElement); } // Initialize animations VisualStateManager.GoToState(this, "NoOverlayAlbum", false); VisualStateManager.GoToState(this, "NoOverlayQueue", false); VisualStateManager.GoToState(this, "NoOverlayMessage", false); Type pageMode = typeof(Album); double scroll = 0d; ITrackContainer navigationContainer = null; Track navigationItem = null; if (_navigationParameter.HasValue && LibraryItemToken.VerifyToken(_navigationParameter.Value)) { var navigationParameter = LibraryItemToken.GetItem(_navigationParameter.Value); // If there is a navigationParameter, use it, and ignore the pageState! if (navigationParameter is Album) { pageMode = typeof(Album); navigationContainer = navigationParameter as ITrackContainer; } else if (navigationParameter is Playlist) { pageMode = typeof(Playlist); navigationContainer = navigationParameter as ITrackContainer; } else if (navigationParameter is Track) { pageMode = typeof(Album); navigationItem = navigationParameter as Track; if (navigationItem != null) { navigationContainer = navigationItem.ContainingAlbum; } } } else if (_pageState != null) { // If no navigationParameter but pageState available, modify UI according to pageState if (_pageState.ContainsKey("PageMode")) { pageMode = Type.GetType((string)_pageState["PageMode"]); } if (_pageState.ContainsKey("AlbumScroll")) { scroll = (double)_pageState["AlbumScroll"]; } } PageMode = pageMode; _pageState = null; _navigationParameter = null; if (navigationContainer != null) { IsAlbumOverlayShown = true; // Delay scrolling after animation await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { CurrentSelection = navigationContainer; albumGridView.ScrollIntoView(CurrentSelection); if (navigationItem != null) { albumDetailListView.SelectedIndex = navigationContainer.IndexOf(navigationItem); albumDetailListView.ScrollIntoView(albumDetailListView.SelectedItem); } }); } else if (scroll > double.Epsilon) // Don't scroll if scroll is negative or less than Epsilon { // Delay scrolling after animation await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { FindVisualChild <ScrollViewer>(albumGridView).ScrollToHorizontalOffset(scroll); }); } }
void fg_processQry(myFgTask.qryType type, object data) { switch (type) { case myFgTask.qryType.updateGUI: updateGUI(null, null); break; case myFgTask.qryType.loadProgress: { Debug.WriteLine("load progress "); } break; case myFgTask.qryType.speech: if (lastTTSstream != null) { // The media object for controlling and playing audio. MediaElement mediaElement = media; //MediaElement mediaElement = new MediaElement(); mediaElement.SetSource(lastTTSstream, lastTTSstream.ContentType); Debug.WriteLine(" + call play()"); mediaElement.Play(); Debug.WriteLine(" + play() return"); } break; case myFgTask.qryType.linebreak: { Paragraph p = new Paragraph(); //curLine.Inlines.Add(new LineBreak()); p.Inlines.Add(curLine); #if false m_srchWorker.ReportProgress(totalLine++, p); #else //srchRtb.Blocks.Add(p); #endif curLine = new Span(); } break; case myFgTask.qryType.hyperlink: { var ch = (char)data; Hyperlink hb = crtBlck(ch); curLine.Inlines.Add(hb); } break; case myFgTask.qryType.run: { var txt = (string)data; curLine.Inlines.Add(new Run { Text = txt }); } break; case myFgTask.qryType.define: { var def = (myDefinition)data; curLine.Inlines.Add(crtDefBlck(def)); } break; case myFgTask.qryType.word: { var wd = (myWord)data; curLine.Inlines.Add(crtWdBlck(wd)); } break; case myFgTask.qryType.scroll: //rtbScroll.ScrollToVerticalOffset(0); //rtbScroll.ChangeView(0, 0, 1); break; } }
/// <summary> /// Initializes a new instance of the <see cref="TransportStreamRecorder"/> class. /// </summary> /// <param name="outputFilePath">The output file path. The extension will be guessed according to the input.</param> /// <param name="media">The parent media element.</param> public TransportStreamRecorder(string outputFilePath, MediaElement media) { FilePath = outputFilePath; Media = media; Media.PacketRead += OnMediaPacketRead; }
/// <summary>Initializes a new instance of the <see cref="MediaElementWrapper"/> class.</summary> public MediaElementWrapper() { #pragma warning disable WPF0041 // Set mutable dependency properties using SetCurrentValue. this.mediaElement = new MediaElement { LoadedBehavior = System.Windows.Controls.MediaState.Manual, UnloadedBehavior = System.Windows.Controls.MediaState.Manual, IsMuted = this.IsMuted, Volume = this.Volume, Balance = this.Balance, ScrubbingEnabled = this.ScrubbingEnabled, Stretch = this.Stretch, StretchDirection = this.StretchDirection, }; #pragma warning restore WPF0041 // Set mutable dependency properties using SetCurrentValue. this.mediaElement.MediaFailed += (o, e) => { this.ResetToNoSource(); this.ReRaiseEvent(o, e); }; this.mediaElement.MediaEnded += (o, e) => { this.SetCurrentValue(StateProperty, MediaState.Stop); this.ReRaiseEvent(o, e); }; this.mediaElement.BufferingStarted += (o, e) => { this.IsBuffering = true; this.updateProgressTimer.Start(); this.ReRaiseEvent(o, e); }; this.mediaElement.BufferingEnded += (o, e) => { this.IsBuffering = true; this.updateProgressTimer.Stop(); this.ReRaiseEvent(o, e); }; this.mediaElement.ScriptCommand += this.ReRaiseEvent; this.mediaElement.MediaOpened += (o, e) => { this.HasMedia = true; this.HasAudio = this.mediaElement.HasAudio; this.HasVideo = this.mediaElement.HasVideo; this.CanPause = this.mediaElement.CanPause; this.NaturalVideoHeight = this.mediaElement.NaturalVideoHeight; this.NaturalVideoWidth = this.mediaElement.NaturalVideoWidth; this.Length = this.mediaElement.NaturalDuration.HasTimeSpan ? this.mediaElement.NaturalDuration.TimeSpan : (TimeSpan?)null; if (this.State == MediaState.Pause || this.State == MediaState.Stop) { this.SetCurrentValue(PositionProperty, TimeSpan.Zero); } this.ReRaiseEvent(o, e); CommandManager.InvalidateRequerySuggested(); }; this.CommandBindings.Add( new CommandBinding(MediaCommands.Play, HandleExecute(this.Play), HandleCanExecute(this.CanPlay))); this.CommandBindings.Add( new CommandBinding( MediaCommands.Pause, HandleExecute(this.PausePlayback), HandleCanExecute(this.CanPausePlayback))); this.CommandBindings.Add( new CommandBinding(MediaCommands.Stop, HandleExecute(this.Stop), HandleCanExecute(this.CanStop))); this.CommandBindings.Add( new CommandBinding( MediaCommands.TogglePlayPause, HandleExecute(this.TogglePlayPause), HandleCanExecute(() => this.CanPlay() || this.CanPausePlayback()))); this.CommandBindings.Add( new CommandBinding( MediaCommands.Rewind, HandleExecute(this.Rewind), HandleCanExecute(this.CanRewind))); this.CommandBindings.Add( new CommandBinding( MediaCommands.IncreaseVolume, HandleExecute(this.IncreaseVolume), HandleCanExecute(this.CanIncreaseVolume))); this.CommandBindings.Add( new CommandBinding( MediaCommands.DecreaseVolume, HandleExecute(this.DecreaseVolume), HandleCanExecute(this.CanDecreaseVolume))); this.CommandBindings.Add( new CommandBinding( MediaCommands.MuteVolume, HandleExecute(this.MuteVolume), HandleCanExecute(this.CanMuteVolume))); this.CommandBindings.Add( new CommandBinding( Commands.UnmuteVolume, HandleExecute(this.UnmuteVolume), HandleCanExecute(this.CanUnmuteVolume))); this.CommandBindings.Add( new CommandBinding( Commands.ToggleMute, HandleExecute(this.ToggleMute), HandleCanExecute(this.CanToggleMute))); this.CommandBindings.Add( new CommandBinding(Commands.Skip, HandleExecute(this.Skip), HandleCanExecute(this.CanSkip))); this.CommandBindings.Add( new CommandBinding( Commands.SkipForward, HandleExecute(this.SkipForward), HandleCanExecute(this.CanSkipForward))); this.CommandBindings.Add( new CommandBinding( Commands.SkipBack, HandleExecute(this.SkipBack), HandleCanExecute(this.CanSkipBack))); this.updatePositionTimer.Tick += (o, e) => this.SetCurrentValue(PositionProperty, this.mediaElement.Position); this.updateProgressTimer.Tick += (o, e) => { this.DownloadProgress = this.mediaElement.DownloadProgress; this.BufferingProgress = this.mediaElement.BufferingProgress; }; }
private void Button_Click_(Object sender, RoutedEventArgs e) { button = (Button)sender; Random random = new Random(); x = random.Next(99); isClicked = true; if (x < y) //Random spawn of red buttons { button.Background = Brushes.DarkRed; Image image = new Image(); image.Stretch = Stretch.Fill; image.BeginInit(); image.Source = new BitmapImage(new Uri(@"C:\Users\rgurbanov\Pictures\red_square.png")); image.EndInit(); button.Content = image; } else //Random spawn of green buttons { button.Background = Brushes.DarkGreen; Image image = new Image(); image.Stretch = Stretch.Fill; image.BeginInit(); image.Source = new BitmapImage(new Uri(@"C:\Users\rgurbanov\Pictures\lnasto_green_square.png")); image.EndInit(); button.Content = image; } if (button.Background == Brushes.DarkRed) { tblock.Text = click_amount.ToString(); if (tblock.Text != null) { click_amount = 1 + Convert.ToInt32(tblock.Text); tblock.Text = click_amount.ToString(); } if (click_amount >= 6) { LosingWin losingWin = new LosingWin(); Image image = new Image(); MediaElement mediaElement = new MediaElement(); image.Stretch = Stretch.Fill; image.BeginInit(); image.Source = new BitmapImage(new Uri(@"C:\Users\rgurbanov\Pictures\neon.jpg")); image.EndInit(); losingWin.Content = image; losingWin.Show(); Close(); } } if (button.Background == Brushes.DarkGreen) { tblockgreen.Text = Green_click_amount.ToString(); if (tblockgreen.Text != null) { green_click_amount = 1 + Convert.ToInt32(tblockgreen.Text); tblockgreen.Text = green_click_amount.ToString(); } if (25 < green_click_amount) { WinWindow win = new WinWindow(); Image image = new Image(); image.Stretch = Stretch.Fill; image.BeginInit(); image.Source = new BitmapImage(new Uri(@"C:\Users\rgurbanov\Pictures\win_image_png.png")); image.EndInit(); win.Content = image; win.Show(); backWindow.Close(); } } //If button clicked once, IsEnabled set false if (isClicked == true) { button.IsEnabled = false; } }
/// <summary> /// Initializes a new instance of the <see cref="WindowsMediaConnector"/> class. /// </summary> /// <param name="parent">The control.</param> public WindowsMediaConnector(MediaElement parent) { Parent = parent; }
/// <summary> /// Starts or resume playing audio file /// </summary> /// <param name="filePath">The name of the audio file</param> /// <summary> /// Starts or resume playing audio file /// </summary> /// <param name="filePath">The name of the audio file</param> public void startPlaying(string filePath) { if (this.recorder != null) { this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorRecordModeSet), false); return; } if (this.player == null || this.player.Source.AbsolutePath.LastIndexOf(filePath) < 0) { try { // this.player is a MediaElement, it must be added to the visual tree in order to play PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame; if (frame != null) { PhoneApplicationPage page = frame.Content as PhoneApplicationPage; if (page != null) { Grid grid = page.FindName("LayoutRoot") as Grid; if (grid != null) { //Microsoft.Xna.Framework.Media.MediaPlayer.Play( this.player = grid.FindName("playerMediaElement") as MediaElement; if (this.player == null) // still null ? { this.player = new MediaElement(); this.player.Name = "playerMediaElement"; grid.Children.Add(this.player); this.player.Visibility = Visibility.Visible; } if (this.player.CurrentState == System.Windows.Media.MediaElementState.Playing) { this.player.Stop(); // stop it! } this.player.Source = null; // Garbage collect it. this.player.MediaOpened += MediaOpened; this.player.MediaEnded += MediaEnded; this.player.MediaFailed += MediaFailed; } } } this.audioFile = filePath; Uri uri = new Uri(filePath, UriKind.RelativeOrAbsolute); if (uri.IsAbsoluteUri) { this.player.Source = uri; } else { using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (isoFile.FileExists(filePath)) { using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(filePath, FileMode.Open, isoFile)) { this.player.SetSource(stream); } } else { Debug.WriteLine("Error: source doesn't exist :: " + filePath); this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, 1), false); return; //throw new ArgumentException("Source doesn't exist"); } } } this.SetState(PlayerState_Starting); } catch (Exception e) { Debug.WriteLine("Error: " + e.Message); this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorStartingPlayback), false); } } else { if (this.state != PlayerState_Running) { this.player.Play(); this.SetState(PlayerState_Running); } else { this.handler.InvokeCustomScript(new ScriptCallback(CallbackFunction, this.id, MediaError, MediaErrorResumeState), false); } } }
public GameRenderer(Size windowBounds, int scaleFactor, MediaElement element) : base(windowBounds, scaleFactor, element) { }
/// <summary> /// Sometimes MediaElement crashes - black window /// I will replace it with the new one /// </summary> internal void RecreateMediaElement(bool flipHorizontally) { try { if (VideoPlayerElement != null) { VideoPlayerElement.Stop(); VideoPlayerElement.Close(); VideoPlayerElement.Clock = null; VideoPlayerElement.Source = null; VideoPlayerElement.Volume = 0; VideoPlayerElement = null; scrollPlayer.Content = null; GC.Collect(); GC.WaitForPendingFinalizers(); } MediaState = MediaState.Manual; VideoPlayerElement = new MediaElement(); VideoPlayerElement.Width = 1920; VideoPlayerElement.Height = 1080; VideoPlayerElement.LoadedBehavior = MediaState.Manual; VideoPlayerElement.Stretch = Stretch.Uniform; VideoPlayerElement.MouseWheel += mePlayer_MouseWheel; Volume = 0; //reset scrollPlayer.Content = VideoPlayerElement; double vOff = _scrollDragger.VerticalOffset; double zoom = _scrollDragger.Zoom; _scrollDragger = new ScrollDragZoom(VideoPlayerElement, scrollPlayer); _scrollDragger.Zoom = zoom; _scrollDragger.VerticalOffset = vOff; _scrollDragger.SizeChangedAction = () => { txtVideoResolution.Text = string.Format("{0:0}x{1:0} ({2:0.0}%)", VideoPlayerElement.ActualWidth, VideoPlayerElement.ActualHeight, 100.0 * _scrollDragger.Zoom); }; //refresh view when change position VideoPlayerElement.ScrubbingEnabled = true; AddFlipXRenderTransform(VideoPlayerElement, flipHorizontally); VideoPlayerElement.MediaOpened += (s, e) => { double zoom_save = _scrollDragger.Zoom; _scrollDragger.NaturalSize = new Size(VideoPlayerElement.NaturalVideoWidth, VideoPlayerElement.NaturalVideoHeight); _scrollDragger.Zoom = zoom_save; MediaState = GetMediaState(VideoPlayerElement); VideoStarted(this); }; VideoPlayerElement.MediaEnded += (s, e) => { VideoEnded(); }; VideoPlayerElement.MediaFailed += (s, e) => { e.Handled = VideoFailed(e, VideoPlayerElement); }; } catch (Exception err) { MessageBox.Show(err.ToString()); } }
async void ButtonSnap_Click(object sender, RoutedEventArgs e) { if (this.mediaCapture == null || !this.isPreviewActive) { return; } // Start countdown... LeftMiddle.Text = topCenter.Text = rightMiddle.Text = bottomCenter.Text = "3"; await WaitMethod(1000); LeftMiddle.Text = topCenter.Text = rightMiddle.Text = bottomCenter.Text = "2"; await WaitMethod(1000); LeftMiddle.Text = topCenter.Text = rightMiddle.Text = bottomCenter.Text = "1"; await WaitMethod(1000); LeftMiddle.Text = topCenter.Text = rightMiddle.Text = bottomCenter.Text = ""; // get media stream properties from the capture device VideoEncodingProperties previewProperties = this.mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties; // create a single preview frame using the specified format VideoFrame videoFrameType = new VideoFrame(BitmapPixelFormat.Bgra8, (int)previewProperties.Width, (int)previewProperties.Height); VideoFrame previewFrame = await this.mediaCapture.GetPreviewFrameAsync(videoFrameType); SoftwareBitmap previewBitmap = previewFrame.SoftwareBitmap; previewFrame.Dispose(); previewFrame = null; if (previewBitmap != null) { int currImageIndex = (this.lastImageIndex + 1) % this.maxFrameCount; // check if previously captured frame should be released SoftwareBitmap existingBitmap = this.bitmapFrames[currImageIndex]; if (existingBitmap != null) { existingBitmap.Dispose(); } // set the current captured bitmap frame this.bitmapFrames[currImageIndex] = previewBitmap; string timeString = DateTime.Now.ToString("yyyyMMdd-HHmm_ss"); string filename = $"PhotoBooth_{timeString}.jpg"; StorageFile file_Save = await Windows.Storage.KnownFolders.SavedPictures.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting); BitmapEncoder encoder = await BitmapEncoder.CreateAsync(Windows.Graphics.Imaging.BitmapEncoder.JpegEncoderId, await file_Save.OpenAsync(FileAccessMode.ReadWrite)); encoder.SetSoftwareBitmap(previewBitmap); await encoder.FlushAsync(); } // camera shutter sound MediaElement click = new MediaElement(); Windows.Storage.StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("Assets"); Windows.Storage.StorageFile file = await folder.GetFileAsync("camera-shutter-click.wav"); var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read); click.SetSource(stream, file.ContentType); click.Play(); }
/// <summary> /// Initializes a new instance of the <see cref="MediaConnector"/> class. /// </summary> /// <param name="parent">The control.</param> public MediaConnector(MediaElement parent) { Parent = parent; }
private void Button_Click(object sender, RoutedEventArgs e) { MediaElement.Play(); RePlayGrid.Visibility = Visibility.Collapsed; }
public MediaElementDemoPage() { element = new MediaElement(); element.HorizontalOptions = new LayoutOptions(LayoutAlignment.Fill, true); element.VerticalOptions = new LayoutOptions(LayoutAlignment.Fill, true); element.MinimumWidthRequest = 320; element.MinimumHeightRequest = 240; element.AutoPlay = false; element.Aspect = Aspect.AspectFill; element.ShowsPlaybackControls = true; element.BackgroundColor = Color.Red; element.MediaEnded += Element_MediaEnded; element.MediaFailed += Element_MediaFailed; element.MediaOpened += Element_MediaOpened; consoleLabel = new Label(); var infoStack = new StackLayout { Orientation = StackOrientation.Horizontal }; var stateLabel = new Label(); stateLabel.SetBinding(Label.TextProperty, new Binding("CurrentState", BindingMode.OneWay, null, null, "s:{0}", element)); var bufferingLabel = new Label(); bufferingLabel.SetBinding(Label.TextProperty, new Binding("BufferingProgress", BindingMode.OneWay, null, null, "b:{0:f2}", element)); var heightLabel = new Label(); heightLabel.SetBinding(Label.TextProperty, new Binding("VideoHeight", BindingMode.OneWay, null, null, "h:{0}", element)); var widthLabel = new Label(); widthLabel.SetBinding(Label.TextProperty, new Binding("VideoWidth", BindingMode.OneWay, null, null, "w:{0}", element)); var durationLabel = new Label(); durationLabel.SetBinding(Label.TextProperty, new Binding("Duration", BindingMode.OneWay, null, null, "d:{0:g}", element)); var volumeLabel = new Label(); volumeLabel.SetBinding(Label.TextProperty, new Binding("Volume", BindingMode.OneWay, null, null, "v:{0}", element)); infoStack.Children.Add(stateLabel); infoStack.Children.Add(bufferingLabel); infoStack.Children.Add(heightLabel); infoStack.Children.Add(widthLabel); infoStack.Children.Add(durationLabel); infoStack.Children.Add(volumeLabel); positionLabel = new Label(); positionLabel.TextColor = Color.Black; //positionLabel.SetBinding(Label.TextProperty, new Binding("Position", BindingMode.OneWay, null, null, "{0:g}", element)); var playButton = new Button(); playButton.Text = "\u25b6\uFE0F"; playButton.FontSize = 48; playButton.HorizontalOptions = new LayoutOptions(LayoutAlignment.Center, true); playButton.Clicked += PlayButton_Clicked; var pauseButton = new Button(); pauseButton.Text = "\u23f8\uFE0F"; pauseButton.FontSize = 48; pauseButton.HorizontalOptions = new LayoutOptions(LayoutAlignment.Center, true); pauseButton.Clicked += PauseButton_Clicked; var stopButton = new Button(); stopButton.Text = "\u23f9\uFE0F"; stopButton.FontSize = 48; stopButton.HorizontalOptions = new LayoutOptions(LayoutAlignment.Center, true); stopButton.Clicked += StopButton_Clicked; var showControlsSwitch = new Switch(); showControlsSwitch.SetBinding(Switch.IsToggledProperty, new Binding("ShowsPlaybackControls", BindingMode.TwoWay, source: element)); var mediaControlStack = new StackLayout(); mediaControlStack.Orientation = StackOrientation.Horizontal; mediaControlStack.HorizontalOptions = new LayoutOptions(LayoutAlignment.Center, false); mediaControlStack.Children.Add(playButton); mediaControlStack.Children.Add(pauseButton); mediaControlStack.Children.Add(stopButton); mediaControlStack.Children.Add(showControlsSwitch); var aspectFitButton = new Button() { Text = "Aspect Fit" }; aspectFitButton.Clicked += (s, e) => { element.Aspect = Aspect.AspectFit; }; var aspectFillButton = new Button() { Text = "Aspect Fill" }; aspectFillButton.Clicked += (s, e) => { element.Aspect = Aspect.AspectFill; }; var fillButton = new Button() { Text = "Fill" }; fillButton.Clicked += (s, e) => { element.Aspect = Aspect.Fill; }; var aspectStack = new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = new LayoutOptions(LayoutAlignment.Center, false) }; aspectStack.Children.Add(aspectFitButton); aspectStack.Children.Add(aspectFillButton); aspectStack.Children.Add(fillButton); var volumeSlider = new Slider() { Minimum = 0, Maximum = 1 }; volumeSlider.Value = 0.1; volumeSlider.ValueChanged += VolumeSlider_ValueChanged; var stack = new StackLayout(); stack.Padding = new Thickness(10); stack.Spacing = 10; stack.HorizontalOptions = new LayoutOptions(LayoutAlignment.Fill, false); stack.VerticalOptions = new LayoutOptions(LayoutAlignment.Fill, false); stack.Children.Add(element); stack.Children.Add(infoStack); stack.Children.Add(positionLabel); stack.Children.Add(mediaControlStack); stack.Children.Add(aspectStack); stack.Children.Add(consoleLabel); stack.Children.Add(new Label() { Text = "Volume:" }); stack.Children.Add(volumeSlider); element.Volume = 0.1; Content = stack; }
public VideoPlayer(MediaElement media, DispatcherTimer timer) { Media = media; Timer = timer; }
private void Play_Click(object sender, RoutedEventArgs e) { MediaElement.Play(); }
/// <summary> /// Plays to end and waits asynchronously. /// </summary> /// <param name="mediaElement">The media element.</param> /// <param name="source">The source to play.</param> /// <returns></returns> public static async Task <MediaElement> PlayToEndAsync(this MediaElement mediaElement, Uri source) { mediaElement.Source = source; return(await mediaElement.WaitToCompleteAsync()); }
void IComponentConnector.Connect(int connectionId, object target) { switch (connectionId) { case 1: LayoutRoot = (Grid)target; break; case 2: MediaEL = (MediaElement)target; MediaEL.MediaOpened += new RoutedEventHandler(MediaEL_MediaOpened); MediaEL.MouseLeftButtonUp += new MouseButtonEventHandler(MediaEL_MouseLeftButtonUp); break; case 3: controlPanel = (StackPanel)target; break; case 4: SPSeekBar = (StackPanel)target; break; case 5: seekBar = (Slider)target; seekBar.AddHandler(Thumb.DragStartedEvent, new DragStartedEventHandler(seekBar_DragStarted)); seekBar.AddHandler(Thumb.DragCompletedEvent, new DragCompletedEventHandler(seekBar_DragCompleted)); break; case 6: btnPlay = (Button)target; btnPlay.Click += new RoutedEventHandler(btnPlay_Click); break; case 7: pause = (Image)target; break; case 8: btnStop = (Button)target; btnStop.Click += new RoutedEventHandler(btnStop_Click); break; case 9: btnMoveBackward = (Button)target; btnMoveBackward.Click += new RoutedEventHandler(btnMoveBackward_Click); break; case 10: btnMoveForward = (Button)target; btnMoveForward.Click += new RoutedEventHandler(btnMoveForward_Click); break; case 11: volumeSlider = (Slider)target; break; default: _contentLoaded = true; break; } }
async Task SpeakTextAsync(string text, MediaElement mediaElement) { IRandomAccessStream stream = await this.SynthesizeTextToSpeechAsync(text); await mediaElement.PlayStreamAsync(stream, true); }
/** * Constructor */ public VideoView() { mMediaElement = new MediaElement(); mView = mMediaElement; /** * the delegates that respond to the widget's events */ // MAW_VIDEO_VIEW_STATE_FINISHED // called when the movie has finished the playback mMediaElement.MediaEnded += new RoutedEventHandler( delegate(object from, RoutedEventArgs args) { // post the event to MoSync runtime Memory eventData = new Memory(12); // set the main event type: MAW_EVENT_VIDEO_STATE_CHANGED const int MAWidgetEventData_widgetEventType = 0; const int MAWidgetEventData_widgetHandle = 4; // set the banner event type: MAW_VIDEO_VIEW_STATE_FINISHED const int MAWidgetEventData_eventType = 8; eventData.WriteInt32(MAWidgetEventData_widgetEventType, MoSync.Constants.MAW_EVENT_VIDEO_STATE_CHANGED); eventData.WriteInt32(MAWidgetEventData_widgetHandle, mHandle); eventData.WriteInt32(MAWidgetEventData_eventType, MoSync.Constants.MAW_VIDEO_VIEW_STATE_FINISHED); mRuntime.PostCustomEvent(MoSync.Constants.EVENT_TYPE_WIDGET, eventData); } ); // end of mMediaElement.MediaEnded // MAW_VIDEO_VIEW_STATE_SOURCE_READY // called when the media stream has been validated and opened, and the file headers have been read mMediaElement.MediaOpened += new RoutedEventHandler( delegate(object from, RoutedEventArgs args) { Memory eventData = new Memory(12); // set the main event type: MAW_EVENT_VIDEO_STATE_CHANGED const int MAWidgetEventData_widgetEventType = 0; const int MAWidgetEventData_widgetHandle = 4; // set the banner event type: MAW_VIDEO_VIEW_STATE_SOURCE_READY const int MAWidgetEventData_eventType = 8; eventData.WriteInt32(MAWidgetEventData_widgetEventType, MoSync.Constants.MAW_EVENT_VIDEO_STATE_CHANGED); eventData.WriteInt32(MAWidgetEventData_widgetHandle, mHandle); eventData.WriteInt32(MAWidgetEventData_eventType, MoSync.Constants.MAW_VIDEO_VIEW_STATE_SOURCE_READY); mRuntime.PostCustomEvent(MoSync.Constants.EVENT_TYPE_WIDGET, eventData); } ); // end of mMediaElement.MediaOpened // MAW_VIDEO_VIEW_STATE_INTERRUPTED // called when there is an error associated with the media source. mMediaElement.MediaFailed += new EventHandler<ExceptionRoutedEventArgs>( delegate(object from, ExceptionRoutedEventArgs args) { // post the event to MoSync runtime Memory eventData = new Memory(12); // set the main event type: MAW_EVENT_VIDEO_STATE_CHANGED const int MAWidgetEventData_widgetEventType = 0; const int MAWidgetEventData_widgetHandle = 4; // set the banner event type: MAW_VIDEO_VIEW_STATE_INTERRUPTED const int MAWidgetEventData_eventType = 8; eventData.WriteInt32(MAWidgetEventData_widgetEventType, MoSync.Constants.MAW_EVENT_VIDEO_STATE_CHANGED); eventData.WriteInt32(MAWidgetEventData_widgetHandle, mHandle); eventData.WriteInt32(MAWidgetEventData_eventType, MoSync.Constants.MAW_VIDEO_VIEW_STATE_INTERRUPTED); mRuntime.PostCustomEvent(MoSync.Constants.EVENT_TYPE_WIDGET, eventData); } ); // end of mMediaElement.MediaFailed }
public static MediaElement CreateMediaElement(long id, int mediaType, int mediaOrigin, string name, long category_id, long album_id, string hash_code, string defaultVideoFormat, long sharingState) { MediaElement mediaElement = new MediaElement(); mediaElement.id = id; mediaElement.mediaType = mediaType; mediaElement.mediaOrigin = mediaOrigin; mediaElement.name = name; mediaElement.category_id = category_id; mediaElement.album_id = album_id; mediaElement.hash_code = hash_code; mediaElement.defaultVideoFormat = defaultVideoFormat; mediaElement.sharingState = sharingState; return mediaElement; }