Example #1
0
 /// <summary>	
 /// <p>[This documentation is preliminary and is subject to change.]</p><p><strong>Applies to: </strong>desktop apps | Metro style apps</p><p>Opens a media resource from a byte stream.</p>	
 /// </summary>	
 /// <param name="byteStreamRef"><dd> <p>A reference to the <strong><see cref="SharpDX.MediaFoundation.IByteStream"/></strong> interface of the byte stream.</p> </dd></param>	
 /// <param name="uRLRef"><dd> <p>The URL of the byte stream.</p> </dd></param>	
 /// <returns><p>If this method succeeds, it returns <strong><see cref="SharpDX.Result.Ok"/></strong>. Otherwise, it returns an <strong><see cref="SharpDX.Result"/></strong> error code.</p></returns>	
 /// <msdn-id>hh447956</msdn-id>	
 /// <unmanaged>HRESULT IMFMediaEngineEx::SetSourceFromByteStream([In] IMFByteStream* pByteStream,[In] wchar_t* pURL)</unmanaged>	
 /// <unmanaged-short>IMFMediaEngineEx::SetSourceFromByteStream</unmanaged-short>	
 public void SetSourceFromByteStream(ByteStream byteStream, string url)
 {
     var bstrUrl = Utilities.StringToHGlobalUni(url);
     try
     {
         //var urlBstr = Marshal.StringToBSTR(url);
         SetSourceFromByteStream_(byteStream.NativePointer, bstrUrl);
     } finally
     {
         Marshal.FreeHGlobal(bstrUrl);
     }
 }
Example #2
0
        static void Main(string[] args)
        {
            // Select a File to play
            var openFileDialog = new OpenFileDialog { Title = "Select a music file", Filter = "Music Files(*.WMA;*.MP3;*.WAV)|*.WMA;*.MP3;*.WAV" };
            var result = openFileDialog.ShowDialog();
            if (result == DialogResult.Cancel)
            {
                return;
            }

            // Initialize MediaFoundation
            MediaManager.Startup();

            // Creates the MediaEngineClassFactory
            var mediaEngineFactory = new MediaEngineClassFactory();

            // Creates MediaEngine for AudioOnly 
            var mediaEngine = new MediaEngine(mediaEngineFactory, null, MediaEngineCreateFlags.AudioOnly);

            // Register our PlayBackEvent
            mediaEngine.PlaybackEvent += OnPlaybackCallback;

            // Query for MediaEngineEx interface
            mediaEngineEx = mediaEngine.QueryInterface<MediaEngineEx>();

            // Opens the file
            var fileStream = openFileDialog.OpenFile();
            
            // Create a ByteStream object from it
            var stream = new ByteStream(fileStream);

            // Creates an URL to the file
            var url = new Uri(openFileDialog.FileName, UriKind.RelativeOrAbsolute);

            // Set the source stream
            mediaEngineEx.SetSourceFromByteStream(stream, url.AbsoluteUri);

            // Wait for MediaEngine to be ready
            if (!eventReadyToPlay.WaitOne(1000))
            {
                Console.WriteLine("Unexpected error: Unable to play this file");
            }

            // Play the music
            mediaEngineEx.Play();

            // Wait until music is stopped.
            while (!isMusicStopped)
            {
                Thread.Sleep(10);
            }
        }
        /// <summary>
        /// Create a topology to be played with a MediaSession from a filepath.
        /// </summary>
        internal static Topology CreateTopology(ByteStream mediaInputStream, out MediaSource mediaSource)
        {
            // collector to dispose all the created Media Foundation native objects.
            var collector = new ObjectCollector();

            // Get the MediaSource object.
            var sourceResolver = new SourceResolver();
            collector.Add(sourceResolver);
            ComObject mediaSourceObject;

            // Try to load music
            try
            {
                mediaSourceObject = sourceResolver.CreateObjectFromStream(mediaInputStream, null, SourceResolverFlags.MediaSource | SourceResolverFlags.ContentDoesNotHaveToMatchExtensionOrMimeType);
            }
            catch (SharpDXException)
            {
                collector.Dispose();
                throw new InvalidOperationException("Music stream format not supported");
            }

            Topology retTopo;

            try
            {
                mediaSource = mediaSourceObject.QueryInterface<MediaSource>();
                collector.Add(mediaSourceObject);

                // Get the PresentationDescriptor
                PresentationDescriptor presDesc;
                mediaSource.CreatePresentationDescriptor(out presDesc);
                collector.Add(presDesc);

                // Create the topology
                MediaFactory.CreateTopology(out retTopo);
                for (var i = 0; i < presDesc.StreamDescriptorCount; i++)
                {
                    Bool selected;
                    StreamDescriptor desc;
                    presDesc.GetStreamDescriptorByIndex(i, out selected, out desc);
                    collector.Add(desc);

                    if (selected)
                    {
                        // Test that the audio file data is valid and supported.
                        var typeHandler = desc.MediaTypeHandler;
                        collector.Add(typeHandler);

                        var majorType = typeHandler.MajorType;

                        if (majorType != MediaTypeGuids.Audio)
                            throw new InvalidOperationException("The music stream is not a valid audio stream.");

                        for (int mType = 0; mType < typeHandler.MediaTypeCount; mType++)
                        {
                            MediaType type;
                            typeHandler.GetMediaTypeByIndex(mType, out type);
                            collector.Add(type);

                            var nbChannels = type.Get(MediaTypeAttributeKeys.AudioNumChannels);
                            if (nbChannels > 2)
                                throw new InvalidOperationException("The provided audio stream has more than 2 channels.");
                        }

                        // create the topology (source,...)
                        TopologyNode sourceNode;
                        MediaFactory.CreateTopologyNode(TopologyType.SourceStreamNode, out sourceNode);
                        collector.Add(sourceNode);

                        sourceNode.Set(TopologyNodeAttributeKeys.Source, mediaSource);
                        sourceNode.Set(TopologyNodeAttributeKeys.PresentationDescriptor, presDesc);
                        sourceNode.Set(TopologyNodeAttributeKeys.StreamDescriptor, desc);

                        TopologyNode outputNode;
                        MediaFactory.CreateTopologyNode(TopologyType.OutputNode, out outputNode);
                        collector.Add(outputNode);

                        Activate activate;
                        MediaFactory.CreateAudioRendererActivate(out activate);
                        collector.Add(activate);
                        outputNode.Object = activate;

                        retTopo.AddNode(sourceNode);
                        retTopo.AddNode(outputNode);
                        sourceNode.ConnectOutput(0, outputNode, 0);
                    }
                }
            }
            finally
            {
                collector.Dispose();
            }

            return retTopo;
        }
        private void ProcessPlayerClosed()
        {
            // The session finished to close, we have to dispose all related object.
            currentMusic = null;

            mediaSessionCallback.Dispose();

            if (mediaSource != null) mediaSource.Shutdown();
            if (mediaSession != null) mediaSession.Shutdown();

            if (streamVolume != null) streamVolume.Dispose();
            if (mediaSource != null) mediaSource.Dispose();
            if (topology != null) topology.Dispose();
            if (mediaSession != null) mediaSession.Dispose();
            if (mediaInputByteStream != null) mediaInputByteStream.Dispose();

            topology = null;
            streamVolume = null;
            mediaSession = null;
            mediaSource = null;
            mediaInputByteStream = null;
            mediaSessionCallback = null;
            isMusicPlayerReady = false;
        }
        /// <summary>
        /// Load a new music into the media session. That is create a new session and a new topology and set the topology of the session.
        /// </summary>
        /// <param name="music"></param>
        private void LoadNewMusic(SoundMusic music)
        {
            if (currentMusic != null || mediaSession != null)
                throw new AudioSystemInternalException("State of the audio engine invalid at the entry of LoadNewMusic.");

            music.Stream.Position = 0;
            mediaInputByteStream = new ByteStream(music.Stream);
            topology = CreateTopology(mediaInputByteStream, out mediaSource);
            MediaFactory.CreateMediaSession(null, out mediaSession);
            mediaSessionCallback = new MediaSessionCallback(mediaSession, OnMediaSessionEvent);
            mediaSession.SetTopology(SessionSetTopologyFlags.None, topology);

            currentMusic = music;
        }
Example #6
0
 public void SetBytestream(IRandomAccessStream streamHandle)
 {
     byteStream = new ByteStream(streamHandle);
     mediaEngineEx.SetSourceFromByteStream(byteStream, Url);
 }
Example #7
0
        static void Main(string[] args)
        {
            // Select a File to play
            var openFileDialog = new OpenFileDialog { Title = "Select a file", Filter = "Media Files(*.WMV;*.MP4;*.AVI)|*.WMV;*.MP4;*.AVI" };
            var result = openFileDialog.ShowDialog();
            if (result == DialogResult.Cancel)
            {
                return;
            }

            // Initialize MediaFoundation
            MediaManager.Startup();

            var renderForm = new SharpDX.Windows.RenderForm();

            device = CreateDeviceForVideo(out dxgiManager);

            // Creates the MediaEngineClassFactory
            var mediaEngineFactory = new MediaEngineClassFactory();
            
            //Assign our dxgi manager, and set format to bgra
            MediaEngineAttributes attr = new MediaEngineAttributes();
            attr.VideoOutputFormat = (int)SharpDX.DXGI.Format.B8G8R8A8_UNorm;
            attr.DxgiManager = dxgiManager;

            // Creates MediaEngine for AudioOnly 
            var mediaEngine = new MediaEngine(mediaEngineFactory, attr, MediaEngineCreateFlags.None);

            // Register our PlayBackEvent
            mediaEngine.PlaybackEvent += OnPlaybackCallback;

            // Query for MediaEngineEx interface
            mediaEngineEx = mediaEngine.QueryInterface<MediaEngineEx>();

            // Opens the file
            var fileStream = openFileDialog.OpenFile();
            
            // Create a ByteStream object from it
            var stream = new ByteStream(fileStream);

            // Creates an URL to the file
            var url = new Uri(openFileDialog.FileName, UriKind.RelativeOrAbsolute);

            // Set the source stream
            mediaEngineEx.SetSourceFromByteStream(stream, url.AbsoluteUri);

            // Wait for MediaEngine to be ready
            if (!eventReadyToPlay.WaitOne(1000))
            {
                Console.WriteLine("Unexpected error: Unable to play this file");
            }

            //Create our swapchain
            swapChain = CreateSwapChain(device, renderForm.Handle);

            //Get DXGI surface to be used by our media engine
            var texture = Texture2D.FromSwapChain<Texture2D>(swapChain, 0);
            var surface = texture.QueryInterface<SharpDX.DXGI.Surface>();

            //Get our video size
            int w, h;
            mediaEngine.GetNativeVideoSize(out w, out h);

            // Play the music
            mediaEngineEx.Play();

            long ts;

            RenderLoop.Run(renderForm, () =>
            {
                //Transfer frame if a new one is available
                if (mediaEngine.OnVideoStreamTick(out ts))
                {
                    mediaEngine.TransferVideoFrame(surface, null, new SharpDX.Rectangle(0, 0, w, h), null);
                }

                swapChain.Present(1, SharpDX.DXGI.PresentFlags.None);
            });

            mediaEngine.Shutdown();
            swapChain.Dispose();
            device.Dispose();
        }
Example #8
0
		/// <summary>
		/// 
		/// </summary>
		private void PlatformInitialize( byte[] bytes, Stream stream, string url )
		{
			if (Topology != null) {
				return;
			}

			MediaFactory.CreateTopology(out _topology);

			SharpDX.MediaFoundation.MediaSource mediaSource;
			{
				SourceResolver resolver = new SourceResolver();
				
				ObjectType otype;
				ComObject source = null;

				if (url!=null) {
					source = resolver.CreateObjectFromURL(url, SourceResolverFlags.MediaSource, null, out otype);
				}

				if (stream!=null) {
					var bs = new ByteStream( stream );
					source = resolver.CreateObjectFromStream(bs, null, SourceResolverFlags.MediaSource, null, out otype);
				}

				if (bytes!=null) {
					var bs = new ByteStream( bytes );
					source = resolver.CreateObjectFromStream(bs, null, SourceResolverFlags.MediaSource|SourceResolverFlags.ContentDoesNotHaveToMatchExtensionOrMimeType, null, out otype);
				}

				if (source==null) {
					throw new ArgumentException("'stream' and 'url' are null!");
				}

				mediaSource = source.QueryInterface<SharpDX.MediaFoundation.MediaSource>();

				
				resolver.Dispose();
				source.Dispose();
			}


			PresentationDescriptor presDesc;
			mediaSource.CreatePresentationDescriptor(out presDesc);
			
			for (var i = 0; i < presDesc.StreamDescriptorCount; i++) {

				RawBool selected = false;
				StreamDescriptor desc;
				presDesc.GetStreamDescriptorByIndex(i, out selected, out desc);
				
				if (selected) {

					TopologyNode sourceNode;
					MediaFactory.CreateTopologyNode(TopologyType.SourceStreamNode, out sourceNode);

					sourceNode.Set(TopologyNodeAttributeKeys.Source, mediaSource);
					sourceNode.Set(TopologyNodeAttributeKeys.PresentationDescriptor, presDesc);
					sourceNode.Set(TopologyNodeAttributeKeys.StreamDescriptor, desc);
					

					TopologyNode outputNode;
					MediaFactory.CreateTopologyNode(TopologyType.OutputNode, out outputNode);

					var majorType = desc.MediaTypeHandler.MajorType;
					
					if (majorType == MediaTypeGuids.Video) {

						Activate activate;
						
						sampleGrabber = new VideoSampleGrabber();

						_mediaType = new MediaType();
						
						_mediaType.Set(MediaTypeAttributeKeys.MajorType, MediaTypeGuids.Video);

						// Specify that we want the data to come in as RGB32.
						_mediaType.Set(MediaTypeAttributeKeys.Subtype, new Guid("00000016-0000-0010-8000-00AA00389B71"));

						MediaFactory.CreateSampleGrabberSinkActivate(_mediaType, SampleGrabber, out activate);
						outputNode.Object = activate;


						long frameSize = desc.MediaTypeHandler.CurrentMediaType.Get<long>(MediaTypeAttributeKeys.FrameSize);

						Width	= (int)(frameSize >> 32);
						Height	= (int) (frameSize & 0x0000FFFF);
					}

					if (majorType == MediaTypeGuids.Audio)
					{
						Activate activate;
						MediaFactory.CreateAudioRendererActivate(out activate);

						outputNode.Object = activate;
					}

					_topology.AddNode(sourceNode);
					_topology.AddNode(outputNode);
					sourceNode.ConnectOutput(0, outputNode, 0);
					

					Duration = new TimeSpan(presDesc.Get<long>(PresentationDescriptionAttributeKeys.Duration));
					

					sourceNode.Dispose();
					outputNode.Dispose();
				}

				desc.Dispose();
			}

			presDesc.Dispose();
			mediaSource.Dispose();


			videoFrame = new DynamicTexture(Game.Instance.RenderSystem, Width, Height, typeof(ColorBGRA), false, false);
		}