public MainWindow()
        {
            InitializeComponent();
            _thisWindow = this;
            BackgroundMusicPlayer = new MediaPlayer();

            #region Music Stuff

            var uri = new Uri(BasePath, "Resources/intro.mp3");
            var mediaPlayer = MainWindow.BackgroundMusicPlayer;
            mediaPlayer.Open(uri);
            mediaPlayer.Play();

            #endregion

            CharacterSelect selectScreen = new CharacterSelect();

            selectScreen.ShowDialog();

            #region Music Stuff

            uri = new Uri(BasePath, "Resources/soundtrack.mp3");
            mediaPlayer.Open(uri);
            mediaPlayer.Play();
            BackgroundPosition = mediaPlayer.Position;

            #endregion

            Start();
        }
Ejemplo n.º 2
0
        public ServiceItem()
        {
            VideoPlayer = new MediaElement();
            AudioPlayer = new MediaPlayer();

            //string loopFilter = "";

            //// specific filters to prevent announcement loops from being included in song loops
            //loopFilter = "background*.mp*";

            //FileInfo[] padsDi = new DirectoryInfo(Properties.Resources.PadPath).GetFiles("*.mp3");
            //FileInfo[] loopsDi = new DirectoryInfo(Properties.Resources.LoopPath).GetFiles(loopFilter);

            //Pads = new List<string>();

            //Pads.Add("");

            //foreach (FileInfo pad in padsDi)
            //    Pads.Add(System.IO.Path.GetFileNameWithoutExtension(pad.Name));

            //Loops = new List<string>();

            //Loops.Add("");

            //foreach (FileInfo loop in loopsDi)
            //    Loops.Add(System.IO.Path.GetFileNameWithoutExtension(loop.Name.Remove(0, loopFilter.Length - 4)));
        }
Ejemplo n.º 3
0
 public void load(MediaPlayer mp,String file)
 {
     mp.Position = TimeSpan.Zero;
     string url = @"C:\Users\Asura\Documents\Visual Studio 2012\Projects\Project Labyrinth(C-Sharp)\Pro Labyrinth(C-Sharp)\Sound\"+file+".wav";
     mp.Open(new Uri(url, UriKind.Relative));
     mp.Volume = 100;
 }
Ejemplo n.º 4
0
		private void PlayVideo ()
		{
			try {
				if (path == "") {
					// Tell the user to provide an audio file URL.
					Toast.MakeText (this, "Please edit MediaPlayer Activity, " + "and set the path variable to your media file path." + " Your media file must be stored on sdcard.", ToastLength.Long).Show ();
					return;
				}
				mediaPlayer = new MediaPlayer (this);
				mediaPlayer.SetDataSource (path);
				mediaPlayer.SetDisplay (sholder);
				mediaPlayer.PrepareAsync ();
				mediaPlayer.SetOnPreparedListener (this);

				mediaPlayer.SetOnTimedTextListener (this);

				// TODO Auto-generated catch block
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.PrintStackTrace ();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.PrintStackTrace ();
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.PrintStackTrace ();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.PrintStackTrace ();
			}
		}
Ejemplo n.º 5
0
        /// <summary>
        /// A media player that takes control of a NotifyIcon icon,
        /// tooltip and balloon to display status.
        /// </summary>
        /// <param name="icon">
        /// The notify icon to use to display status.
        /// </param>
        public Player(NotifyIcon icon)
        {
            notifyIcon = icon;

            player = new MediaPlayer();
            player.BufferingStarted += OnBufferingStarted;
            player.BufferingEnded += OnBufferingEnded;
            player.MediaEnded += OnMediaEnded;
            player.MediaFailed += OnMediaFailed;

            idleIcon = Util.ResourceAsIcon("GaGa.NotifyIconPlayer.Resources.Idle.ico");
            playingIcon = Util.ResourceAsIcon("GaGa.NotifyIconPlayer.Resources.Playing.ico");
            playingMutedIcon = Util.ResourceAsIcon("GaGa.NotifyIconPlayer.Resources.Playing-muted.ico");

            bufferingIcons = new Icon[] {
                Util.ResourceAsIcon("GaGa.NotifyIconPlayer.Resources.Buffering1.ico"),
                Util.ResourceAsIcon("GaGa.NotifyIconPlayer.Resources.Buffering2.ico"),
                Util.ResourceAsIcon("GaGa.NotifyIconPlayer.Resources.Buffering3.ico"),
                Util.ResourceAsIcon("GaGa.NotifyIconPlayer.Resources.Buffering4.ico"),
            };

            bufferingIconTimer = new DispatcherTimer(DispatcherPriority.Background);
            bufferingIconTimer.Interval = TimeSpan.FromMilliseconds(300);
            bufferingIconTimer.Tick += OnBufferingIconTimerTick;
            currentBufferingIcon = 0;

            source = null;
            isIdle = true;

            UpdateIcon();
        }
Ejemplo n.º 6
0
 public static void RunTests() {
     var player = new MediaPlayer();
     player.Play();
     player.Pause();
     player.Stop();
     player.AllSongs.TrackNames.PrintCollection();
 }
Ejemplo n.º 7
0
 public MainPage()
 {
     this.InitializeComponent();
     this.NavigationCacheMode = NavigationCacheMode.Required;
     initValue();
     mediaPlayer = BackgroundMediaPlayer.Current;
 }
        public MainWindow()
        {
            InitializeComponent();

            OscServer oscServer;
            
            oscServer = new OscServer(TransportType.Udp, IPAddress.Loopback, Port);

            oscServer.FilterRegisteredMethods = false;
			oscServer.RegisterMethod(AliveMethod);
            oscServer.RegisterMethod(TestMethod);
            oscServer.BundleReceived += new EventHandler<OscBundleReceivedEventArgs>(oscServer_BundleReceived);
			oscServer.MessageReceived += new EventHandler<OscMessageReceivedEventArgs>(oscServer_MessageReceived);
            oscServer.ReceiveErrored += new EventHandler<Bespoke.Common.ExceptionEventArgs>(oscServer_ReceiveErrored);
            oscServer.ConsumeParsingExceptions = false;

            oscServer.Start();
            Console.WriteLine("Server started.");

            //Start playing audio
            string audioFileName = "/file/path";
            mp = new MediaPlayer();
            mp.MediaOpened += new EventHandler(mp_MediaOpened);
            bool isPaused = false;
            bool isPlaying = false;
        }
Ejemplo n.º 9
0
        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);

            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);

            if(mLibVLC == null)
            {
                mLibVLC = new LibVLCLibVLC();
                mMediaPlayer = new MediaPlayer(mLibVLC);
            }

            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById<Button> (Resource.Id.myButton);

            button.Click += delegate {
                button.Text = string.Format ("{0} clicks!", count++);

                var m = new MediaLibVLC(mLibVLC, Android.Net.Uri.Parse("http://www.montemagno.com/sample.mp3"));

                // Tell the media player to play the new Media.
                mMediaPlayer.Media = m;

                // Finally, play it!
                mMediaPlayer.Play();
            };
        }
        /// <summary>
        /// Pause
        /// </summary>
        private void Pause()
        {
            if (_mediaPlayer == null)
                _mediaPlayer = BackgroundMediaPlayer.Current;

            _mediaPlayer.Pause();
        }
        public void SetUpProtectionManager(MediaPlayer mediaPlayer)
        {
            Log("Enter SetUpProtectionManager");

            if(mediaPlayer == null)
                throw new ArgumentException("SetUpProtectionManager was passed a null MediaPlayer");
            
            Log("Creating protection system mappings...");
            var protectionManager = new MediaProtectionManager();

            protectionManager.ComponentLoadFailed += new ComponentLoadFailedEventHandler(ProtectionManager_ComponentLoadFailed);
            protectionManager.ServiceRequested += new ServiceRequestedEventHandler(ProtectionManager_ServiceRequested);

            // The code here is mandatory and should be just copied directly over to the app
            // Ref: https://msdn.microsoft.com/en-us/library/windows/desktop/aa376846%28v=vs.85%29.aspx

            // Setup PlayReady as the ProtectionSystem to use by mediaFoundation: 
            var contentProtectionSystems = new PropertySet();
            contentProtectionSystems.Add(PlayReadyWinRTTrustedInput);
            protectionManager.Properties.Add(MediaProtectionSystemIdMapping, contentProtectionSystems);
            protectionManager.Properties.Add(MediaProtectionSystemId);
            protectionManager.Properties.Add(MediaProtectionContainerGuid);

            mediaPlayer.ProtectionManager = protectionManager;

            Log("Leave SetUpProtectionManager");
        }
Ejemplo n.º 12
0
        public MainViewModel()
        {
            Player = new MediaPlayer();
            SourceBands = new SortedSet<Band>();
            Collections = new List<Collection>();
               /* Bands = GetBandsFromCollection();
            Songs = GetSongsFromCollection();
            Albums = GetAlbumsFromCollection();*/

            CurrentSong = Song.EmptySong;
            Status = SongStatus.Stopped;
            PlayList = new List<Song>();
            PlayQueue = new Queue<Song>();

            SearchField = new MusicSearchField(SourceBands, Bands);

            // Fill play button images
            /*PlayerControlsSourceImage = new BitmapImage(new Uri("pack://application:,,,/Resources/playerControls-.png"));

            var pauseStateImage = new CroppedBitmap(PlayerControlsSourceImage, new Int32Rect(0, 0, 48, 48));
            PauseStateBitmap = pauseStateImage;

            var stopStateImage = new CroppedBitmap(PlayerControlsSourceImage, new Int32Rect(58, 0, 48, 48));
            StopStateBitmap = stopStateImage;*/
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MainWindow" /> class.
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();

            // var streamURI = ipi.StreamUri; // new Uri(@"http://127.0.0.1:8072");
            var streamURI = new Uri(@"http://127.0.0.1:8072");

            var savedStreams = SavedUriHandler.Streams.ToList();

            var lss = new LivestreamerSettings() { StreamUri = savedStreams[0].StreamUri, StreamQuality = savedStreams[0].Quality };
            var lss2 = new LivestreamerSettings() { StreamUri = savedStreams[1].StreamUri, StreamQuality = savedStreams[1].Quality };

            launch = new LSLauncher(lss);
            launch.Launch();

            MediaPlayer player = new MediaPlayer();
            player.Open(streamURI);
            VideoDrawing vd = new VideoDrawing();
            vd.Rect = new Rect(0, 0, 1920, 1080);
            vd.Player = player;
            player.Play();
            videoImage.Drawing = vd;
            vd.Freeze();
            player.Freeze();
        }
Ejemplo n.º 14
0
        public MainWindow()
        {
            InitializeComponent();

            musicPlayer = new MediaPlayer();

            try
            {
                musicLibrary = new MusicLib();
            }
            catch(Exception e)
            {
                MessageBox.Show("Songs could not be uploaded.");
            }

            musicLibrary.AddPlaylist("All Music");

            foreach (string s in musicLibrary.SongIds)
            {
                musicLibrary.AddSongToPlaylist(Int32.Parse(s), "All Music");
            }

            playlistListBox.ItemsSource = musicLibrary.Playlists;

            musicDataGrid.ItemsSource = musicLibrary.Songs.DefaultView;
        }
Ejemplo n.º 15
0
		protected override void OnCreate(Bundle bundle)
		{
			base.OnCreate(bundle);

			this.SetContentView(Resource.Layout.Main);

			var playButton = this.FindViewById<Button>(Resource.Id.PlayPauseButton);
			var stopButton = this.FindViewById<Button>(Resource.Id.StopButton);
			var searchView = this.FindViewById<SearchView>(Resource.Id.SearchView);
			this.listView = this.FindViewById<ListView>(Resource.Id.listView1);
			this.timeDisplay = this.FindViewById<TextView>(Resource.Id.TimeDisplay);
			this.adapter = new SongResultsAdapter(this, new Song[0]);
			this.player = new MediaPlayer();
			
			this.switcher = this.FindViewById<ViewSwitcher>(Resource.Id.ViewSwitcher);
			this.loadingMessage = this.FindViewById<TextView>(Resource.Id.LoadingMessage);
			
			playButton.Click += this.PlayButton_Click;
			stopButton.Click += this.StopButton_Click;
			searchView.QueryTextSubmit += this.SearchView_QueryTextSubmit;
			searchView.QueryTextChange += this.SearchView_QueryTextChange;
			this.listView.ItemClick += this.ListView_ItemClick;
			this.player.BufferingUpdate += this.Player_BufferingUpdate;
			this.player.Error += this.Player_Error;

			this.ShowListViewMessage("Write in the search box to start.");
		}
Ejemplo n.º 16
0
 private void Scenario8_Loaded(object sender, RoutedEventArgs e)
 {
     mediaPlayer = new MediaPlayer();
     mediaPlayer.Source = MediaSource.CreateFromUri(new Uri("https://mediaplatstorage1.blob.core.windows.net/windows-universal-samples-media/elephantsdream-clip-h264_sd-aac_eng-aac_spa-aac_eng_commentary-srt_eng-srt_por-srt_swe.mkv"));
     mediaPlayer.Play();
     BindMediaPlayerToUIElement(mediaPlayer, mediaPlayerButton);
 }
Ejemplo n.º 17
0
		public virtual void playRingtone()
		{
			AudioManager audioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);

			// Honour silent mode
			switch (audioManager.RingerMode)
			{
				case AudioManager.RINGER_MODE_NORMAL:
					mPlayer = new MediaPlayer();
					mPlayer.AudioStreamType = AudioManager.STREAM_RING;

					try
					{
						mPlayer.setDataSource(mContext, Uri.parse("android.resource://" + mContext.PackageName + "/" + R.raw.phone_loud1));
						mPlayer.prepare();
					}
					catch (IOException e)
					{
						Log.e(LOG_TAG, "Could not setup media player for ringtone");
						mPlayer = null;
						return;
					}
					mPlayer.Looping = true;
					mPlayer.start();
					break;
			}
		}
        // Media set up

        //------------------------------------------------------------------------------
        //
        // StartPlayback
        //
        // News up a MediaPlayer, creates a playback item then 
        // MediaPlayer hands out a surface that can be put on brush
        // We call this below when we set up the tree init the composition
        //
        //------------------------------------------------------------------------------
        private void StartPlayback()
        {


            // MediaPlayer set up with a create from URI
            _mediaPlayer = new MediaPlayer();

            // Get a source from a URI. This could also be from a file via a picker or a stream

            var source = MediaSource.CreateFromUri(new Uri("http://go.microsoft.com/fwlink/?LinkID=809007&clcid=0x409"));
            var item = new MediaPlaybackItem(source);
            _mediaPlayer.Source = item;

            // MediaPlayer supports many of the starndard MediaElement vars like looping
            _mediaPlayer.IsLoopingEnabled = true;

            // Get the surface from MediaPlayer and put it on a brush
            _videoSurface = _mediaPlayer.GetSurface(_compositor);
            _videoVisual.Brush = _compositor.CreateSurfaceBrush(_videoSurface.CompositionSurface);

            // Play the video on app run.

            PlayVideo();

        }
Ejemplo n.º 19
0
        public MainWindow()
        {
            InitializeComponent();
            TasktrayIcon = new NotifyIcon
            {
                Text = "Kbtter",
                Visible = true,
                Icon = new Icon("trayicon.ico")
            };

            Player = new MediaPlayer();

            UploadImagePath = new Dictionary<string, Stream>();
            UploadImageDialog = new OpenFileDialog();
            UploadImageDialog.AddExtension = true;
            UploadImageDialog.Multiselect = true;
            UploadImageDialog.Title = "アップロードする画像を選択";
            UploadImageDialog.Filter = "対応している画像ファイル|*.png;*.jpg;*.jpeg;*.gif|PNGイメージ|*.png|JPEGイメージ|*.jpg;*.jpeg|GIFイメージ|*.gif";

            IronPythonEngine = Python.CreateEngine();
            IronPythonEngine.Runtime.LoadAssembly(this.GetType().Assembly);
            IronPythonEngine.Runtime.LoadAssembly(Assembly.LoadFrom("TweetSharp.dll"));

            TweetPlugins = new List<IKbtterOnTweet>();
            RetweetPlugins = new List<IKbtterOnRetweet>();
            FavoritePlugins = new List<IKbtterOnFavorite>();
            UnfavoritePlugins = new List<IKbtterOnUnfavorite>();
            InitializePlugins = new List<IKbtterOnInitialize>();
            WindowPlugins = new List<IKbtterCallable>();

            Settings = new Config();
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Constructor
        /// </summary>
        internal MediaEventsHelper(MediaPlayer mediaPlayer) 
        {
            _mediaOpened = new DispatcherOperationCallback(OnMediaOpened); 
            this.DispatcherMediaOpened += _mediaOpened; 

            _mediaFailed = new DispatcherOperationCallback(OnMediaFailed); 
            this.DispatcherMediaFailed += _mediaFailed;

            _mediaPrerolled = new DispatcherOperationCallback(OnMediaPrerolled);
            this.DispatcherMediaPrerolled += _mediaPrerolled; 

            _mediaEnded = new DispatcherOperationCallback(OnMediaEnded); 
            this.DispatcherMediaEnded += _mediaEnded; 

            _bufferingStarted = new DispatcherOperationCallback(OnBufferingStarted); 
            this.DispatcherBufferingStarted += _bufferingStarted;

            _bufferingEnded = new DispatcherOperationCallback(OnBufferingEnded);
            this.DispatcherBufferingEnded += _bufferingEnded; 

            _scriptCommand = new DispatcherOperationCallback(OnScriptCommand); 
            this.DispatcherScriptCommand += _scriptCommand; 

            _newFrame = new DispatcherOperationCallback(OnNewFrame); 
            this.DispatcherMediaNewFrame += _newFrame;

            SetSender(mediaPlayer);
        } 
Ejemplo n.º 21
0
 /// <summary>
 /// Fired when MediaPlayer is ready to play the track
 /// </summary>
 void MediaPlayer_MediaOpened(MediaPlayer sender, object args)
 {
     // wait for media to be ready
     sender.Play();
     Debug.WriteLine("New Track" + this.CurrentTrackName);
     TrackChanged.Invoke(this, CurrentTrackName);
 }
Ejemplo n.º 22
0
        void HandleMediaPlayerMediaOpened(MediaPlayer sender, object args)
        {
            if (isFirstOpen)
            {
                isFirstOpen = false;
                double percentage = ApplicationSettings.GetSettingsValue<double>(ApplicationSettings.CURRENT_TRACK_PERCENTAGE, 0.0);
                ApplicationSettings.PutSettingsValue(ApplicationSettings.CURRENT_TRACK_PERCENTAGE, 0.0);

                if (percentage > 0)
                {
                    Logger.Current.Init(LogType.PlayAction);

                    Logger.Current.Log(new CallerInfo(), LogLevel.Info, "Length Total {0}", mediaPlayer.NaturalDuration.Ticks);

                    mediaPlayer.Position = TimeSpan.FromTicks((long)(mediaPlayer.NaturalDuration.Ticks * percentage));
                }
            }

            int trackId = ApplicationSettings.GetSettingsValue<int>(ApplicationSettings.CURRENT_PLAYQUEUE_POSITION, 0);
            Logger.Current.Init(LogType.PlayAction);

            Logger.Current.Log(new CallerInfo(), LogLevel.Info, "Trying to play row {0}", trackId);

            playingTrack = TrackInfo.TrackInfoFromRowId(trackId);
            TrackChanged.Invoke(this, playingTrack);

            if (playAfterOpen)
            {
                sender.Play();
            }
            else
            {
                playAfterOpen = true;
            }
        }
Ejemplo n.º 23
0
		public bool OnInfo (MediaPlayer mp, int what, int extra)
		{
			switch (what) {
			case MediaPlayer.MediaInfoBufferingStart:
				if (mVideoView.IsPlaying) {
					mVideoView.Pause ();
					pb.Visibility = ViewStates.Visible;
					downloadRateView.Text = "";
					loadRateView.Text = "";
					downloadRateView.Visibility = ViewStates.Visible;
					loadRateView.Visibility = ViewStates.Visible;

				}
				break;
			case MediaPlayer.MediaInfoBufferingEnd:
				mVideoView.Start ();
				pb.Visibility = ViewStates.Gone;
				downloadRateView.Visibility = ViewStates.Gone;
				loadRateView.Visibility = ViewStates.Gone;
				break;
			case MediaPlayer.MediaInfoDownloadRateChanged:
				downloadRateView.Text = "" + extra + "kb/s" + "  ";
				break;
			}
			return true;
		}
Ejemplo n.º 24
0
 public Mp3PlayerPlugin()
 {
     player = new MediaPlayer();
     player.Volume = 100;
     FriendlyName = "Basic Mp3 Player";
     FriendlyStatus = "TODO: Return Current Status";
 }
Ejemplo n.º 25
0
 public void Play(string filename, Action<Exception> failed = null)
 {
     Application.Current.Dispatcher.BeginInvoke(new Action(() =>
     {
         try
         {
             var path = string.Format(soundFilePath, "wav", filename);
             if (!System.IO.File.Exists(path))
             {
                 path = string.Format(soundFilePath, "mp3", filename);
             }
             if (!System.IO.File.Exists(path))
             {
                 throw new System.IO.FileNotFoundException();
             }
             if (mediaPlayer == null)
             {
                 mediaPlayer = new MediaPlayer { Volume = 1 };
             }
             mediaPlayer.Open(new Uri(path, UriKind.Absolute));
             mediaPlayer.Play();
         }
         catch (Exception ex)
         {
             AMing.Plugins.Core.GenericMessager.Current.SendToException(ex);
             if (failed != null)
                 failed(ex);
         }
     }));
 }
Ejemplo n.º 26
0
 public Mp3PlayerPlugin()
 {
     player = new MediaPlayer();
     player.Volume = 100;
     FriendlyName = "Basic Mp3 Player";
     FriendlyStatus = "No Status Set";
 }
Ejemplo n.º 27
0
        public AudioController()
        {
            App.Startup();

            #region Rpc
            _acRpcServer = new AudioControllerRpcServer(this);
            _achRpcClient = new AudioControllerHandlerRpcClient();
            _audioControllerHandler = _achRpcClient.Service;
            #endregion

            _stateMachine = BuildStateMachine();
            _mediaEnvironment.RegisterDefaultCodecs();
            _playModeManager = IoC.Get<IPlayModeManager>();

            _mediaPlayer = BackgroundMediaPlayer.Current;
            _mediaPlayer.AutoPlay = false;
            _mediaPlayer.MediaOpened += mediaPlayer_MediaOpened;
            _mediaPlayer.MediaFailed += mediaPlayer_MediaFailed;
            _mediaPlayer.MediaEnded += mediaPlayer_MediaEnded;
            _playbackSession = _mediaPlayer.PlaybackSession;
            _playbackSession.PlaybackStateChanged += playbackSession_PlaybackStateChanged;
            _playbackSession.NaturalDurationChanged += playbackSession_NaturalDurationChanged;
            _playbackSession.SeekCompleted += playbackSession_SeekCompleted;

            _mtService = new MediaTransportService(_mediaPlayer.SystemMediaTransportControls);
            _mtService.IsEnabled = _mtService.IsPauseEnabled = _mtService.IsPlayEnabled = true;
            _mtService.ButtonPressed += _mtService_ButtonPressed;

            NotifyReady();
        }
Ejemplo n.º 28
0
        /// <summary>
        /// A media player that is controlled from a notify icon
        /// using the mouse. Takes control of the notifyicon icon,
        /// tooltip and balloon to display status.
        /// </summary>
        /// <param name="icon">
        /// The notify icon that controls playback.
        /// </param>
        public Player(NotifyIcon icon)
        {
            notifyIcon = icon;
            notifyIcon.MouseClick += OnMouseClick;

            player = new MediaPlayer();
            player.BufferingStarted += OnBufferingStarted;
            player.BufferingEnded += OnBufferingEnded;
            player.MediaEnded += OnMediaEnded;
            player.MediaFailed += OnMediaFailed;

            source = null;
            isIdle = true;

            idleIcon = Utils.ResourceAsIcon("GaGa.Resources.idle.ico");
            playingIcon = Utils.ResourceAsIcon("GaGa.Resources.playing.ico");
            playingMutedIcon = Utils.ResourceAsIcon("GaGa.Resources.playing-muted.ico");

            bufferingIcons = new Icon[] {
                Utils.ResourceAsIcon("GaGa.Resources.buffering1.ico"),
                Utils.ResourceAsIcon("GaGa.Resources.buffering2.ico"),
                Utils.ResourceAsIcon("GaGa.Resources.buffering3.ico"),
                Utils.ResourceAsIcon("GaGa.Resources.buffering4.ico"),
            };

            bufferingIconTimer = new DispatcherTimer();
            bufferingIconTimer.Interval = TimeSpan.FromMilliseconds(300);
            bufferingIconTimer.Tick += bufferingIconTimer_Tick;

            currentBufferingIcon = 0;

            UpdateIcon();
        }
        public override StartVideoPlaybackMessage GetStartVideoPlaybackMessageWithCurrentPosition(MediaPlayer mediaPlayer)
        {
            var message = base.GetStartVideoPlaybackMessageWithCurrentPosition(mediaPlayer);
            message.FullScreen = false;

            return message;
        }
 virtual public void TitleChanged(MediaPlayer mediaPlayer, int newTitle)
 {
 }
 virtual public void PausableChanged(MediaPlayer mediaPlayer, int newSeekable)
 {
 }
 virtual public void PositionChanged(MediaPlayer mediaPlayer, float newPosition)
 {
 }
 virtual public void TimeChanged(MediaPlayer mediaPlayer, long newTime)
 {
 }
 virtual public void Finished(MediaPlayer mediaPlayer)
 {
 }
Ejemplo n.º 35
0
        public async Task Play()
        {
            manuallyPaused = false;
            if (mediaPlayer != null && MediaPlayerState == PlaybackStateCompat.StatePaused)
            {
                //We are simply paused so just start again
                mediaPlayer.Start();
                UpdatePlaybackState(PlaybackStateCompat.StatePlaying);
                StartNotification();

                //Update the metadata now that we are playing
                UpdateMediaMetadataCompat();
                return;
            }

            if (mediaPlayer != null)
            {
                mediaPlayer.Reset();
                mediaPlayer.Release();
                mediaPlayer = null;
            }

            //if (mediaPlayer == null)
            InitializePlayer();

            //if(mediaSessionCompat == null)
            InitMediaSession();

            if (mediaPlayer.IsPlaying)
            {
                UpdatePlaybackState(PlaybackStateCompat.StatePlaying);
                return;
            }

            try
            {
                MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever();

                await mediaPlayer.SetDataSourceAsync(ApplicationContext, Android.Net.Uri.Parse(audioUrl));

                await metaRetriever.SetDataSourceAsync(audioUrl, new Dictionary <string, string>());

                var focusResult = audioManager.RequestAudioFocus(this, Stream.Music, AudioFocus.Gain);
                if (focusResult != AudioFocusRequest.Granted)
                {
                    //could not get audio focus
                    Console.WriteLine("Could not get audio focus");
                }

                UpdatePlaybackState(PlaybackStateCompat.StateBuffering);
                mediaPlayer.PrepareAsync();

                AquireWifiLock();
                UpdateMediaMetadataCompat(metaRetriever);
                StartNotification();

                byte[] imageByteArray = metaRetriever.GetEmbeddedPicture();
                if (imageByteArray == null)
                {
                    Bitmap coverBitmap = GetCurrentTrackCover();
                    if (coverBitmap != null)
                    {
                        Cover = coverBitmap;
                    }
                    else
                    {
                        Cover = await BitmapFactory.DecodeResourceAsync(Resources, Resource.Drawable.ButtonStar);
                    }
                }
                else
                {
                    Cover = await BitmapFactory.DecodeByteArrayAsync(imageByteArray, 0, imageByteArray.Length);
                }
            }
            catch (Exception ex)
            {
                UpdatePlaybackState(PlaybackStateCompat.StateStopped);

                if (mediaPlayer != null)
                {
                    mediaPlayer.Reset();
                    mediaPlayer.Release();
                    mediaPlayer = null;
                }

                //unable to start playback log error
                Console.WriteLine(ex);
            }
        }
 virtual public void Forward(MediaPlayer mediaPlayer)
 {
 }
        // === Synthetic/semantic events ============================================

        virtual public void NewMedia(MediaPlayer mediaPlayer)
        {
        }
 virtual public void SnapshotTaken(MediaPlayer mediaPlayer, String filename)
 {
 }
 virtual public void Playing(MediaPlayer mediaPlayer)
 {
 }
 virtual public void Buffering(MediaPlayer mediaPlayer, float newCache)
 {
 }
 virtual public void Opening(MediaPlayer mediaPlayer)
 {
 }
 virtual public void EndOfSubItems(MediaPlayer mediaPlayer)
 {
 }
 virtual public void SubItemFinished(MediaPlayer mediaPlayer, int subItemIndex)
 {
 }
 virtual public void MediaStateChanged(MediaPlayer mediaPlayer, int newState)
 {
 }
 virtual public void MediaMetaChanged(MediaPlayer mediaPlayer, int metaType)
 {
 }
 virtual public void MediaParsedChanged(MediaPlayer mediaPlayer, int newStatus)
 {
 }
 virtual public void MediaFreed(MediaPlayer mediaPlayer)
 {
 }
        // === Events relating to the current media =================================

        virtual public void MediaSubItemAdded(MediaPlayer mediaPlayer, IntPtr subItem)
        {
        }
 virtual public void MediaDurationChanged(MediaPlayer mediaPlayer, long newDuration)
 {
 }
Ejemplo n.º 50
0
        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            {
                Exit();
            }

            if (!controller.inGame)
            {
                MediaPlayer.Stop();
            }
            else
            {
                if (MediaPlayer.State == MediaState.Stopped)
                {
                    MediaPlayer.Play(background_music);
                }
            }

            player.shipUpdate(gameTime, controller);
            //testAsteroid.asteroidUpdate(gameTime);
            controller.conUpdate(gameTime);
            // for (int i = 0; i < controller.asteroids.Count; i++)
            // {
            //     controller.asteroids[i].asteroidUpdate(gameTime);
            // }
            foreach (Asteroid asteroid in controller.asteroids)
            {
                asteroid.asteroidUpdate(gameTime);
                if (asteroid.position.X < -asteroid.radius)
                {
                    controller.score  += 10;
                    asteroid.offscreen = true;
                }
                // radius of the selected asteroid + radius player
                int sum = asteroid.radius + 30;
                if (Vector2.Distance(asteroid.position, player.position) <= sum)
                {
                    controller.inGame = false;
                    player.position   = Ship.defaultPosition;
                    controller.asteroids.Clear();
                    break;
                }
            }

            // on regarde les projectiles
            foreach (Weapon weapon in Weapon.Weapons)
            {
                weapon.Update(gameTime);
                // on verifie si un projectile touche 1 asteroid
                foreach (Asteroid asteroid in controller.asteroids)
                {
                    int sum = asteroid.radius + weapon.Radius;
                    if (Vector2.Distance(asteroid.position, weapon.Position) <= sum)
                    {
                        // activer le detonateur
                        weapon.DelayBeforeExplosion(asteroid);
                    }

                    if (asteroid.resistance <= 0)
                    {
                        asteroid.offscreen = true;
                    }
                }
            }

            // voir definition sur les prédicats
            try
            {
                controller.asteroids.RemoveAll(ast => ast.offscreen);
                Weapon.Weapons.RemoveAll(weapon => (weapon.IsDestroyed || weapon.Position.X > (1280 + weapon.Radius)));
            }
            catch (Exception)
            { }
            base.Update(gameTime);
        }
 virtual public void Error(MediaPlayer mediaPlayer)
 {
 }
Ejemplo n.º 52
0
        private async void BT_Start_Click(object sender, RoutedEventArgs e)
        {
            string originalButtonContent = (string)BT_Start.Content;

            BT_Start.Content   = "This process take a while...";
            BT_Start.IsEnabled = false;
            string path = TBX_Path.Text;

            if (File.Exists(path))
            {
                PB_Main.Visibility      = Visibility.Visible;
                PB_Main.IsIndeterminate = true;
                if (Directory.Exists("pre-process"))
                {
                    Directory.Delete("pre-process", true);
                }
                Directory.CreateDirectory("pre-process");
                var uri    = new System.Uri(GetLocalFullPath("complete.wav"));
                var player = new MediaPlayer
                {
                    Volume = 0
                };
                player.Open(uri);
                var    video       = new VideoInfo(path);
                int    totalFrames = 0;
                double fps         = video.FrameRate;
                string ffmpegPath  = GetLocalFullPath("assets\\x86\\ffmpeg.exe");
                string ffprobePath = GetLocalFullPath("assets\\x86\\ffprobe.exe");
                string ffmpegArgs  = $"-i \"{path}\" -vf fps={fps} \"{GetLocalFullPath("pre-process\\out%07d.png")}\"";
                string ffprobeArgs = $"-i \"{path}\" -print_format json -loglevel fatal -show_streams -count_frames -select_streams v";

                string dainPath       = GetLocalFullPath("assets\\dain-ncnn-vulkan.exe");
                string dainInputPath  = GetLocalFullPath("pre-process");
                string dainOutputPath = GetLocalFullPath("output-frames");
                string audioPath      = GetLocalFullPath("output.mp3");

                FileInfo outputFileWithAudio = new FileInfo(GetLocalFullPath("output.mp4"));
                string   ffmpegJoinArgs      = $"-r {fps*2} -i \"{dainOutputPath}\\%08d.png\" -i \"{audioPath}\" \"{outputFileWithAudio}\" -c:a copy -c:v libx264 -pix_fmt yuv420p -crf 24 -y";

                ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_VideoController");
                int gpuCount = 0;
                foreach (ManagementObject obj in searcher.Get())
                {
                    if (obj["CurrentBitsPerPixel"] != null && obj["CurrentHorizontalResolution"] != null)
                    {
                        gpuCount++;
                    }
                }
                StringBuilder graphicsOptionBuilder = new StringBuilder();
                for (int i = 0; i < gpuCount; i++)
                {
                    graphicsOptionBuilder.Append(i.ToString());
                    if (i != gpuCount - 1)
                    {
                        graphicsOptionBuilder.Append(",");
                    }
                }

                string   dainArgs      = $"-i \"{dainInputPath}\" -o \"{dainOutputPath}\" -g {graphicsOptionBuilder} -v";
                FileInfo audioFileInfo = null;
                await Task.Run(() =>
                {
                    if (File.Exists(audioPath))
                    {
                        File.Delete(audioPath);
                    }
                    audioFileInfo         = new FFMpeg().ExtractAudio(video, new FileInfo(audioPath));
                    ProcessStartInfo info = new ProcessStartInfo(ffmpegPath, ffmpegArgs);
                    StartProcess(info);
                });

                await Task.Run(() =>
                {
                    ProcessStartInfo info       = new ProcessStartInfo(ffprobePath, ffprobeArgs);
                    info.RedirectStandardOutput = true;
                    info.UseShellExecute        = false;
                    info.WindowStyle            = ProcessWindowStyle.Hidden;
                    var process = Process.Start(info);
                    childs.Add(process);
                    process.WaitForExit();

                    string infoStr = process.StandardOutput.ReadToEnd();
                    var videoInfo  = JsonConvert.DeserializeObject <JsonArgs.VideoInfo.Root>(infoStr);
                    int.TryParse(videoInfo.streams[0].nb_frames, out totalFrames);
                });

                if (Directory.Exists("output-frames"))
                {
                    Directory.Delete("output-frames", true);
                }
                Directory.CreateDirectory("output-frames");
                bool isCompleted = false;
                await Task.Run(async() =>
                {
                    ProcessStartInfo info = new ProcessStartInfo(dainPath, dainArgs);
                    await Dispatcher.InvokeAsync(() => {
                        PB_Main.IsIndeterminate = false;
                    });
                    _ = Task.Run(async() =>
                    {
                        while (!isCompleted)
                        {
                            int maxFrame      = totalFrames * 2;
                            int currentFrame  = Directory.GetFiles("output-frames").Length; await Task.Delay(1000);
                            double percentage = ((double)currentFrame / maxFrame) * 100.0;
                            await Dispatcher.InvokeAsync(() =>
                            {
                                PB_Main.Value = percentage;
                            });
                            await Task.Delay(500);
                        }
                    });
                    StartProcess(info);
                    isCompleted = true;
                    await Dispatcher.InvokeAsync(() =>
                    {
                        PB_Main.IsIndeterminate = true;
                    });
                });

                Directory.Delete(GetLocalFullPath("pre-process"), true);
                Clipboard.SetText("\"" + ffmpegPath + "\" " + ffmpegJoinArgs);
                await Task.Run(() =>
                {
                    ProcessStartInfo info = new ProcessStartInfo(ffmpegPath, ffmpegJoinArgs);
                    StartProcess(info);
                    File.Delete(audioFileInfo.FullName);
                    Directory.Delete(GetLocalFullPath("output-frames"), true);
                    File.Delete(audioPath);
                });

                player.Volume = 1;
                player.Play();
                PB_Main.Visibility = Visibility.Collapsed;

                string         outputDefaultFileName = System.IO.Path.GetFileNameWithoutExtension(path);
                SaveFileDialog sfd = new SaveFileDialog
                {
                    DefaultExt = "mp4",
                    Filter     = "Video file (*.mp4)|*.mp4|All files (*.*)|*.*",
                    FileName   = $"{outputDefaultFileName}-2x.mp4"
                };
                if (sfd.ShowDialog() == true)
                {
                    File.Move(outputFileWithAudio.FullName, sfd.FileName);
                }
                else
                {
                    outputFileWithAudio.Delete();
                }

                BT_Start.IsEnabled = true;
                BT_Start.Content   = originalButtonContent;
            }
            else
            {
                MessageBox.Show("Target file does not exist", "Error", MessageBoxButton.OK, MessageBoxImage.Error); BT_Start.IsEnabled = true;
            }
        }
Ejemplo n.º 53
0
 private Sound(MediaPlayer player)
 {
     _player = player;
 }
 virtual public void Paused(MediaPlayer mediaPlayer)
 {
 }
Ejemplo n.º 55
0
        public MainWindow()
        {
            InitializeComponent();
            GD.date_last_save = DateTime.Now;
            //génération de la première population
            _population = new Population();
            createMidiFiles();

            // Initialisation graphique
            Width                = GD.WINDOW_WIDTH;
            Height               = GD.WINDOW_HEIGHT;
            ResizeMode           = ResizeMode.CanMinimize;
            WindowStyle          = WindowStyle.None;
            Background           = new SolidColorBrush(Color.FromArgb(0xFF, 0x16, 0x16, 0x16));
            Icon                 = new BitmapImage(new Uri("pack://application:,,,/ressources/icon.ico"));
            MouseLeftButtonDown += MainWindow_MouseDown;

            // Main Canvas Initialization
            AddChild(GD.MainCanvas);
            GD.MainCanvas.Width  = GD.WINDOW_WIDTH;
            GD.MainCanvas.Height = GD.WINDOW_HEIGHT;
            GD.MainCanvas.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
            GD.MainCanvas.VerticalAlignment   = System.Windows.VerticalAlignment.Top;

            // Head Text
            Rectangle rect_head = new Rectangle();

            rect_head.Width  = 390;
            rect_head.Height = 35;
            rect_head.Fill   = new ImageBrush(new BitmapImage(new Uri("pack://application:,,,/ressources/titre_evomelo.png")));
            Canvas.SetTop(rect_head, (5));
            Canvas.SetLeft(rect_head, (30));
            GD.MainCanvas.Children.Add(rect_head);

            // Exit button
            GD.bt_Exit.Width  = 20;
            GD.bt_Exit.Height = 20;
            GD.bt_Exit.Fill   = new ImageBrush(new BitmapImage(new Uri("pack://application:,,,/ressources/icon_cross.png")));
            GD.bt_Exit.Name   = "icon_cross";
            GD.bt_Exit.MouseLeftButtonDown += ExitButton_MouseDown;
            GD.bt_Exit.MouseEnter          += Button_MouseEnter;
            GD.bt_Exit.MouseLeave          += Button_MouseLeave;
            Canvas.SetTop(GD.bt_Exit, (10));
            Canvas.SetRight(GD.bt_Exit, (10));
            GD.MainCanvas.Children.Add(GD.bt_Exit);

            // Cadres
            for (int n = 0; n < 11; n++)
            {
                if (n < 10)
                {
                    GD.borderIndividus[n]                 = new Border();
                    GD.borderIndividus[n].Width           = GD.WINDOW_WIDTH - 60;
                    GD.borderIndividus[n].Height          = 35;
                    GD.borderIndividus[n].Background      = new SolidColorBrush(Color.FromArgb(0xFF, 0x11, 0x11, 0x11));
                    GD.borderIndividus[n].BorderThickness = new Thickness(0);
                    GD.borderIndividus[n].BorderBrush     = new SolidColorBrush(Color.FromArgb(0xFF, 0x22, 0x22, 0x22));
                    Canvas.SetTop(GD.borderIndividus[n], (50 + (n * 50)));
                    Canvas.SetLeft(GD.borderIndividus[n], (30));
                    GD.MainCanvas.Children.Add(GD.borderIndividus[n]);

                    // Draw Preview
                    drawPreview(n);

                    // Play button
                    GD.rectPlayIndividus[n]        = new Rectangle();
                    GD.rectPlayIndividus[n].Width  = 27;
                    GD.rectPlayIndividus[n].Height = 27;
                    GD.rectPlayIndividus[n].Fill   = new ImageBrush(new BitmapImage(new Uri("pack://application:,,,/ressources/icon_play.png")));
                    GD.rectPlayIndividus[n].MouseLeftButtonDown += PlayButton_MouseDown;
                    GD.rectPlayIndividus[n].MouseEnter          += Button_MouseEnter;
                    GD.rectPlayIndividus[n].MouseLeave          += Button_MouseLeave;
                    GD.rectPlayIndividus[n].Name = "icon_play";
                    Canvas.SetTop(GD.rectPlayIndividus[n], (54 + (n * 50)));
                    Canvas.SetRight(GD.rectPlayIndividus[n], (35));
                    GD.MainCanvas.Children.Add(GD.rectPlayIndividus[n]);

                    // Star buttons
                    for (int n2 = 0; n2 < 5; n2++)
                    {
                        // Star button
                        GD.rectStars[(n * 5 + n2)]        = new Rectangle();
                        GD.rectStars[(n * 5 + n2)].Width  = 32;
                        GD.rectStars[(n * 5 + n2)].Height = 24;
                        GD.rectStars[(n * 5 + n2)].Fill   = new ImageBrush(new BitmapImage(new Uri("pack://application:,,,/ressources/icon_star_empty.png")));
                        GD.rectStars[(n * 5 + n2)].MouseLeftButtonDown += StarButton_MouseDown;
                        GD.rectStars[(n * 5 + n2)].MouseEnter          += Button_MouseEnter;
                        GD.rectStars[(n * 5 + n2)].MouseLeave          += Button_MouseLeave;
                        GD.rectStars[(n * 5 + n2)].Name = "icon_star_empty";
                        Canvas.SetTop(GD.rectStars[(n * 5 + n2)], (55 + (n * 50)));
                        Canvas.SetLeft(GD.rectStars[(n * 5 + n2)], (220 + (32 * n2)));
                        GD.MainCanvas.Children.Add(GD.rectStars[(n * 5 + n2)]);
                    }

                    // Save button
                    GD.rectSaveIndividus[n]                      = new Rectangle();
                    GD.rectSaveIndividus[n].Width                = 25;
                    GD.rectSaveIndividus[n].Height               = 25;
                    GD.rectSaveIndividus[n].Fill                 = new ImageBrush(new BitmapImage(new Uri("pack://application:,,,/ressources/icon_save.png")));
                    GD.rectSaveIndividus[n].MouseEnter          += Button_MouseEnter;
                    GD.rectSaveIndividus[n].MouseLeave          += Button_MouseLeave;
                    GD.rectSaveIndividus[n].MouseLeftButtonDown += SaveButton_MouseDown;
                    GD.rectSaveIndividus[n].Name                 = "icon_save";
                    Canvas.SetTop(GD.rectSaveIndividus[n], (55 + (n * 50)));
                    Canvas.SetRight(GD.rectSaveIndividus[n], (246));
                    GD.MainCanvas.Children.Add(GD.rectSaveIndividus[n]);

                    // Here : Generation of each track
                    // Generation of preview graph
                }
                else
                {
                    GD.bt_Generation.Width       = 390;
                    GD.bt_Generation.Height      = 35;
                    GD.bt_Generation.Fill        = new ImageBrush(new BitmapImage(new Uri("pack://application:,,,/ressources/button_generation_err.png")));
                    GD.bt_Generation.MouseEnter += Button_MouseEnter;
                    GD.bt_Generation.MouseLeave += Button_MouseLeave;
                    GD.bt_Generation.Name        = "button_generation_err";
                    GD.bt_Generation.MouseDown  += generationButton_MouseDown;
                    Canvas.SetTop(GD.bt_Generation, (50 + (n * 50)));
                    Canvas.SetLeft(GD.bt_Generation, (30));
                    GD.MainCanvas.Children.Add(GD.bt_Generation);
                }
            }

            // Initialisation du lecteur
            _mplayer             = new MediaPlayer();
            _mplayer.MediaEnded += mplayer_MediaEnded;
            _isPlaying           = false;

            // On s'abonne à la fermeture du programme pour pouvoir nettoyer le répertoire et les fichiers midi
            this.Closed += MainWindow_Closed;
        }
 virtual public void Stopped(MediaPlayer mediaPlayer)
 {
 }
 virtual public void Backward(MediaPlayer mediaPlayer)
 {
 }
        // === Events relating to the media player ==================================

        virtual public void MediaChanged(MediaPlayer mediaPlayer, IntPtr media, string mrl)
        {
        }
Ejemplo n.º 59
0
 public void OnPrepared(MediaPlayer mp)
 {
     //Mediaplayer is prepared start track playback
     mp.Start();
     UpdatePlaybackState(PlaybackStateCompat.StatePlaying);
 }
Ejemplo n.º 60
-1
        public WindowsMediaPlayerModel()
        {
            _mediaPlayer = new MediaPlayer();
            IsPlaying = false;

            _mediaPlayer.MediaEnded += (sender, args) => Stop();
        }