internal async Task HandleHeadersAsync(KeyValuePair <string, string>[] headers)
        {
            if (headers == null)
            {
                throw new ArgumentNullException(nameof(headers), "Headers are null");
            }
            if (headers.Length == 0)
            {
                throw new ArgumentException(paramName: "headers", message: "Header count is 0");
            }

            await DetectAudioEncodingPropertiesAsync(headers);

            if (cancelTokenSource.IsCancellationRequested)
            {
                return;
            }

            if (audioProperties == null)
            {
                throw new InvalidOperationException("Unable to detect audio encoding properties.");
            }

            var audioStreamDescriptor = new AudioStreamDescriptor(audioProperties);

            MediaStreamSource                  = new MediaStreamSource(audioStreamDescriptor);
            MediaStreamSource.Paused          += MediaStreamSource_Paused;
            MediaStreamSource.Starting        += MediaStreamSource_Starting;
            MediaStreamSource.Closed          += MediaStreamSource_Closed;
            MediaStreamSource.SampleRequested += MediaStreamSource_SampleRequested;
        }
示例#2
0
        public override Windows.Media.Core.IMediaStreamDescriptor CreateMediaStreamDescriptor()
        {
            AudioEncodingProperties properties = null;

            using (FlacHeaderReader header = new FlacHeaderReader(new MemoryStream(TrackEntry.CodecPrivate), true))
            {
                while (header.Read())
                {
                }
                flacInfo = header.Streaminfo;

                properties = AudioEncodingProperties.CreatePcm(
                    (uint)flacInfo.SampleRate,
                    (uint)flacInfo.ChannelsCount,
                    (uint)flacInfo.BitsPerSample);
            }

            var descriptor = new AudioStreamDescriptor(properties);

            if (TrackEntry.CodecPrivate != null)
            {
                properties.SetFormatUserData(TrackEntry.CodecPrivate);
            }

            return(descriptor);
        }
示例#3
0
        /// <summary>
        /// Получить медиа источник.
        /// </summary>
        public async Task <MediaStreamSource> GetSource()
        {
            if (_mediaSource != null)
            {
                return(_mediaSource);
            }

            try
            {
                if (_file == null)
                {
                    string cacheFileName = $"{Track.VKInfo.OwnerID} {Track.VKInfo.ID}.vksm";
                    _fileData = await _musicCacheService.GetVKSaverFile(cacheFileName);

                    if (_fileData == null)
                    {
                        return(null);
                    }
                }
                else
                {
                    _fileData = new VKSaverAudioFile(_file);
                }

                _fileStream = await _fileData.GetContentStreamAsync();

                var metadata = await _fileData.GetMetadataAsync();

                _currentBitrate  = metadata.Track.EncodingBitrate;
                _currentChannels = metadata.Track.ChannelCount;

                _bufferSize = (int)(_currentBitrate / 8) * (BUFFERED_TIME_SECONDS + 3);
                _buffer     = new byte[_bufferSize];

                _sampleDuration = TimeSpan.FromMilliseconds(SAMPLE_SIZE / (_currentBitrate / 1000 / 8));

                var audioProperties = AudioEncodingProperties.CreateMp3(
                    metadata.Track.SampleRate, _currentChannels, _currentBitrate);

                var audioDescriptor = new AudioStreamDescriptor(audioProperties);
                _mediaSource = new MediaStreamSource(audioDescriptor);

                _mediaSource.CanSeek = true;
                _mediaSource.MusicProperties.Title  = Track.Title;
                _mediaSource.MusicProperties.Artist = Track.Artist;
                _mediaSource.MusicProperties.Album  = "ВКачай";
                _mediaSource.Duration   = TimeSpan.FromTicks(metadata.Track.Duration);
                _mediaSource.BufferTime = TimeSpan.FromSeconds(BUFFERED_TIME_SECONDS);

                _mediaSource.Starting        += MediaSource_Starting;
                _mediaSource.SampleRequested += MediaSource_SampleRequested;
                _mediaSource.Closed          += MediaSource_Closed;

                return(_mediaSource);
            }
            catch (Exception) { return(null); }
        }
示例#4
0
        public MainPage()
        {
            this.InitializeComponent();

            var protectionManager = new MediaProtectionManager();

            //A setting to tell MF that we are using PlayReady.
            var props = new Windows.Foundation.Collections.PropertySet();

            props.Add("{F4637010-03C3-42CD-B932-B48ADF3A6A54}", "Windows.Media.Protection.PlayReady.PlayReadyWinRTTrustedInput");
            protectionManager.Properties.Add("Windows.Media.Protection.MediaProtectionSystemIdMapping", props);
            protectionManager.Properties.Add("Windows.Media.Protection.MediaProtectionSystemId", "{F4637010-03C3-42CD-B932-B48ADF3A6A54}");

            //Maps the container guid from the manifest or media segment
            protectionManager.Properties.Add("Windows.Media.Protection.MediaProtectionContainerGuid", "{9A04F079-9840-4286-AB92-E65BE0885F95}");

            protectionManager.ServiceRequested    += ProtectionManager_ServiceRequested;
            protectionManager.ComponentLoadFailed += ProtectionManager_ComponentLoadFailed;

            // media player
            MediaPlayer mediaPlayer = new MediaPlayer();

            mediaPlayer.MediaOpened += MediaPlayer_MediaOpened;
            mediaPlayer.MediaFailed += MediaPlayer_MediaFailed;

            // media source
#if true
            AudioEncodingProperties audioProperties = AudioEncodingProperties.CreateAacAdts(44100, 1, 72000);
            Guid MF_SD_PROTECTED = new Guid(0xaf2181, 0xbdc2, 0x423c, 0xab, 0xca, 0xf5, 0x3, 0x59, 0x3b, 0xc1, 0x21);
            //audioProperties.Properties.Add(MF_SD_PROTECTED, 1 /* true ? doc says UINT32 - treat as a boolean value */);
            audioProperties.Properties.Add(MF_SD_PROTECTED, PropertyValue.CreateUInt32(1));
            AudioStreamDescriptor audioStreamDescriptor = new AudioStreamDescriptor(audioProperties);
            foreach (var prop in audioStreamDescriptor.EncodingProperties.Properties)
            {
                Log(prop.Key.ToString() + " => " + prop.Value.ToString());
            }
            MediaStreamSource mediaStreamSource = new MediaStreamSource(audioStreamDescriptor);
            mediaStreamSource.MediaProtectionManager = protectionManager;   // protection manager is on the media stream source
            mediaStreamSource.SampleRequested       += MediaStreamSource_SampleRequested;
            mediaStreamSource.Starting += MediaStreamSource_Starting;
            MediaSource mediaSource = MediaSource.CreateFromMediaStreamSource(mediaStreamSource);
#else
            MediaSource mediaSource = MediaSource.CreateFromUri(new Uri("http://profficialsite.origin.mediaservices.windows.net/c51358ea-9a5e-4322-8951-897d640fdfd7/tearsofsteel_4k.ism/manifest(format=mpd-time-csf)"));
            mediaPlayer.ProtectionManager = protectionManager;              // protection manager is on the media player
#endif

            // play !
            m_mediaPlayerElement.SetMediaPlayer(mediaPlayer);
            mediaPlayer.Source = mediaSource;
            mediaPlayer.Play();
        }
        protected void UpdateAudioStreamsMenu()
        {
            // Some updates could be avoided if we tracked a "dirty" flag and break execution if !dirty
            lock (_syncObj)
            {
                IPlayerContextManager playerContextManager = ServiceRegistration.Get <IPlayerContextManager>();
                int numActivePlayers     = playerContextManager.NumActivePlayerContexts;
                int numberOfAudioStreams = GetTotalNumberOfAudioStreams();

                _audioStreamsMenu.Clear();
                for (int i = 0; i < numActivePlayers; i++)
                {
                    IPlayerContext pc = playerContextManager.GetPlayerContext(i);
                    if (pc == null || !pc.IsActive)
                    {
                        continue;
                    }
                    IPlayer player = pc.CurrentPlayer;
                    AudioStreamDescriptor         currentAudioStream;
                    IList <AudioStreamDescriptor> asds = new List <AudioStreamDescriptor>(pc.GetAudioStreamDescriptors(out currentAudioStream));
                    foreach (AudioStreamDescriptor asd in asds)
                    {
                        string playedItem = player == null ? null : player.MediaItemTitle ?? pc.Name;
                        string choiceItemName;
                        int    count = asds.Count;
                        if (numActivePlayers > 1 && count > 1 && count != numberOfAudioStreams)
                        {
                            // Only display the playedItem name if more than one player is able to provide audio streams. If a single player provides
                            // multiple streams, they will be distinguished by the VideoPlayer.
                            choiceItemName = playedItem + ": " + asd.AudioStreamName;
                        }
                        else
                        {
                            choiceItemName = count != numberOfAudioStreams ? playedItem : asd.AudioStreamName;
                        }

                        AudioStreamDescriptor asdClosureCopy = asd;
                        ListItem item = new ListItem(Consts.KEY_NAME, choiceItemName)
                        {
                            Command  = new MethodDelegateCommand(() => ChooseAudioStream(asdClosureCopy)),
                            Selected = asd == currentAudioStream,
                        };
                        item.AdditionalProperties[Consts.KEY_NAVIGATION_MODE] = NavigationMode.ExitPCWorkflow;
                        _audioStreamsMenu.Add(item);
                    }
                }
                _audioStreamsMenu.FireChange();
            }
        }
示例#6
0
        public override Windows.Media.Core.IMediaStreamDescriptor CreateMediaStreamDescriptor()
        {
            Audio audioInfo  = TrackEntry.Audio;
            var   properties = AudioEncodingProperties.CreateMp3(
                (uint)audioInfo.SamplingFrequency,
                (uint)audioInfo.Channels,
                (uint)audioInfo.BitDepth);
            var descriptor = new AudioStreamDescriptor(properties);

            if (TrackEntry.CodecPrivate != null)
            {
                properties.SetFormatUserData(TrackEntry.CodecPrivate);
            }
            return(descriptor);
        }
        protected void UpdateAudioStreamsMenu()
        {
            // Some updates could be avoided if we tracked a "dirty" flag and break execution if !dirty
            lock (_syncObj)
            {
                IPlayerManager        playerManager        = ServiceRegistration.Get <IPlayerManager>();
                IPlayerContextManager playerContextManager = ServiceRegistration.Get <IPlayerContextManager>();

                _audioStreamsMenu.Clear();
                for (int i = 0; i < playerManager.NumActiveSlots; i++)
                {
                    IPlayerContext                pc     = playerContextManager.GetPlayerContext(i);
                    IPlayer                       player = pc.CurrentPlayer;
                    AudioStreamDescriptor         currentAudioStream;
                    IList <AudioStreamDescriptor> asds = new List <AudioStreamDescriptor>(pc.GetAudioStreamDescriptors(out currentAudioStream));
                    foreach (AudioStreamDescriptor asd in asds)
                    {
                        string playedItem = player == null ? null : player.MediaItemTitle ?? pc.Name;
                        string choiceItemName;
                        if (asds.Count > 1)
                        {
                            // Only display the audio stream name if the player has more than one audio stream
                            choiceItemName = playedItem + ": " + asd.AudioStreamName;
                        }
                        else
                        {
                            choiceItemName = playedItem;
                        }
                        AudioStreamDescriptor asdClosureCopy = asd;
                        ListItem item = new ListItem(Consts.KEY_NAME, choiceItemName)
                        {
                            Command  = new MethodDelegateCommand(() => ChooseAudioStream(asdClosureCopy)),
                            Selected = asd == currentAudioStream,
                        };
                        item.AdditionalProperties[Consts.KEY_NAVIGATION_MODE] = NavigationMode.ExitPCWorkflow;
                        _audioStreamsMenu.Add(item);
                    }
                }
                _audioStreamsMenu.FireChange();
            }
        }
示例#8
0
        public override Windows.Media.Core.IMediaStreamDescriptor CreateMediaStreamDescriptor()
        {
            Audio audioInfo = TrackEntry.Audio;
            //var properties = AudioEncodingProperties.CreatePcm(
            //                (uint)audioInfo.SamplingFrequency,
            //                (uint)audioInfo.Channels,
            //                audioInfo.BitDepth > 0 ? (uint)audioInfo.BitDepth : 16);
            var properties = AudioEncodingProperties.CreatePcm(
                Math.Max((UInt32)audioInfo.SamplingFrequency, (UInt32)8000),
                2,
                16);

            var descriptor = new AudioStreamDescriptor(properties);

            if (TrackEntry.CodecPrivate != null)
            {
                properties.SetFormatUserData(TrackEntry.CodecPrivate);
            }

            return(descriptor);
        }
        public void PlaySound(int samplingRate, byte[] pcmData)
        {
            AudioEncodingProperties audioProps = AudioEncodingProperties.CreatePcm((uint)samplingRate, 1, 16);
            AudioStreamDescriptor audioDesc = new AudioStreamDescriptor(audioProps);
            MediaStreamSource mss = new MediaStreamSource(audioDesc);
            
            bool samplePlayed = false;
            mss.SampleRequested += (sender, args) =>
            {
                if (samplePlayed)
                    return;

                IBuffer ibuffer = pcmData.AsBuffer();
                MediaStreamSample sample = MediaStreamSample.CreateFromBuffer(ibuffer, TimeSpan.Zero);
                sample.Duration = TimeSpan.FromSeconds(pcmData.Length / 2.0 / samplingRate);
                args.Request.Sample = sample;
                samplePlayed = true;
            };

            mediaElement.SetMediaStreamSource(mss);
        }
示例#10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DialogAudioOutputMediaSource"/> class.
        /// </summary>
        /// <param name="stream"> The DialogAudioOutputStream to use as input for this MediaElement. </param>
        public DialogAudioOutputMediaSource(DialogAudioOutputStream stream)
        {
            Contract.Requires(stream != null);

            this.sourceStream = stream;

            // Here we precompute constants for the duration of this source to avoid doing it every sample
            var encoding = stream.Format.Encoding;

            this.sampleDuration = SampleDurationForEncoding(encoding);
            var bytesInSample = (uint)(this.sampleDuration.TotalSeconds * encoding.Bitrate / 8);

            var sourceDescriptor  = new AudioStreamDescriptor(stream.Format.Encoding);
            var mediaStreamSource = new MediaStreamSource(sourceDescriptor)
            {
                IsLive     = true,
                BufferTime = TimeToBuffer,
            };

            mediaStreamSource.SampleRequested += this.OnMediaSampleRequested;
            this.WindowsMediaSource            = MediaSource.CreateFromIMediaSource(mediaStreamSource);
        }
        public ICollection <AudioStreamDescriptor> GetAvailableAudioStreams(out AudioStreamDescriptor currentAudioStream)
        {
            currentAudioStream = null;
            IPlayerManager playerManager = ServiceRegistration.Get <IPlayerManager>();
            ICollection <AudioStreamDescriptor> result = new List <AudioStreamDescriptor>();
            int audioSlotIndex = playerManager.AudioSlotIndex;

            for (int i = 0; i < 2; i++)
            {
                IPlayerContext playerContext = GetPlayerContext(i);
                if (playerContext == null)
                {
                    continue;
                }
                AudioStreamDescriptor current;
                CollectionUtils.AddAll(result, playerContext.GetAudioStreamDescriptors(out current));
                if (audioSlotIndex == i)
                {
                    currentAudioStream = current;
                }
            }
            return(result);
        }
示例#12
0
        /// <summary>
        /// Initialize the media element for playback
        /// </summary>
        /// <param name="streamConfig">Object containing stream configuration details</param>
        void InitializeMediaPlayer(LimelightStreamConfiguration streamConfig, AvStreamSource streamSource)
        {
            this._streamSource = streamSource;

            AudioEncodingProperties audioProperties = AudioEncodingProperties.CreatePcm(48000, 2, 16);

            VideoEncodingProperties videoProperties = VideoEncodingProperties.CreateUncompressed(MediaEncodingSubtypes.H264Es,
                                                                                                 (uint)streamConfig.GetWidth(), (uint)streamConfig.GetHeight());

            videoProperties.ProfileId = H264ProfileIds.High;

            _videoDesc = new VideoStreamDescriptor(videoProperties);
            _audioDesc = new AudioStreamDescriptor(audioProperties);

            _mss                  = new MediaStreamSource(_videoDesc, _audioDesc);
            _mss.BufferTime       = TimeSpan.Zero;
            _mss.CanSeek          = false;
            _mss.Duration         = TimeSpan.Zero;
            _mss.SampleRequested += _mss_SampleRequested;

            // Set for low latency playback
            StreamDisplay.RealTimePlayback = true;

            // Set the audio category to take advantage of hardware audio offload
            StreamDisplay.AudioCategory = AudioCategory.ForegroundOnlyMedia;

            // Render on the full window to avoid extra compositing
            StreamDisplay.IsFullWindow = true;

            // Disable built-in transport controls
            StreamDisplay.AreTransportControlsEnabled = false;

            // Start playing right away
            StreamDisplay.AutoPlay = true;

            StreamDisplay.SetMediaStreamSource(_mss);
        }
示例#13
0
        /// <summary>
        /// Initialize the media element for playback
        /// </summary>
        /// <param name="streamConfig">Object containing stream configuration details</param>
        void InitializeMediaPlayer(LimelightStreamConfiguration streamConfig, AvStreamSource streamSource)
        {
            this._streamSource = streamSource;

            AudioEncodingProperties audioProperties = AudioEncodingProperties.CreatePcm(48000, 2, 16);

            VideoEncodingProperties videoProperties = VideoEncodingProperties.CreateUncompressed(MediaEncodingSubtypes.H264Es,
                (uint)streamConfig.GetWidth(), (uint)streamConfig.GetHeight());
            videoProperties.ProfileId = H264ProfileIds.High;

            _videoDesc = new VideoStreamDescriptor(videoProperties);
            _audioDesc = new AudioStreamDescriptor(audioProperties);

            _mss = new MediaStreamSource(_videoDesc, _audioDesc);
            _mss.BufferTime = TimeSpan.Zero;
            _mss.CanSeek = false;
            _mss.Duration = TimeSpan.Zero;
            _mss.SampleRequested += _mss_SampleRequested;

            // Set for low latency playback
            StreamDisplay.RealTimePlayback = true;

            // Set the audio category to take advantage of hardware audio offload
            StreamDisplay.AudioCategory = AudioCategory.ForegroundOnlyMedia;

            // Render on the full window to avoid extra compositing
            StreamDisplay.IsFullWindow = true;

            // Disable built-in transport controls
            StreamDisplay.AreTransportControlsEnabled = false;

            // Start playing right away
            StreamDisplay.AutoPlay = true;

            StreamDisplay.SetMediaStreamSource(_mss);
        }
        protected void UpdatePlayerSlotAudioMenu()
        {
            // Some updates could be avoided if we tracked a "dirty" flag and break execution if !dirty
            lock (_syncObj)
            {
                IPlayerManager        playerManager        = ServiceRegistration.Get <IPlayerManager>();
                IPlayerContextManager playerContextManager = ServiceRegistration.Get <IPlayerContextManager>();

                _playerSlotAudioMenu.Clear();
                IPlayerContext pc = _playerAudioMenuPlayerContext;
                if (pc == null || !pc.IsActive)
                {
                    LeaveAudioMenuWorkflow();
                    return;
                }
                IPlayer player = pc.CurrentPlayer;
                AudioStreamDescriptor         currentAudioStream;
                IList <AudioStreamDescriptor> asds = new List <AudioStreamDescriptor>(pc.GetAudioStreamDescriptors(out currentAudioStream));
                foreach (AudioStreamDescriptor asd in asds)
                {
                    string playedItem = player == null ? null : player.MediaItemTitle ?? pc.Name;
                    string choiceItemName;
                    if (asds.Count > 1)
                    {
                        // Only display the audio stream name if the player has more than one audio stream
                        choiceItemName = playedItem + ": " + asd.AudioStreamName;
                    }
                    else
                    {
                        choiceItemName = playedItem;
                    }
                    AudioStreamDescriptor asdClosureCopy = asd;
                    ListItem item = new ListItem(Consts.KEY_NAME, choiceItemName)
                    {
                        Command  = new MethodDelegateCommand(() => ChooseAudioStream(asdClosureCopy)),
                        Selected = asd == currentAudioStream,
                    };
                    item.AdditionalProperties[Consts.KEY_NAVIGATION_MODE] = NavigationMode.ExitPCWorkflow;
                    _playerSlotAudioMenu.Add(item);
                }
                if (_showToggleMute)
                {
                    ListItem item;
                    if (playerManager.Muted)
                    {
                        item = new ListItem(Consts.KEY_NAME, Consts.RES_MUTE_OFF)
                        {
                            Command  = new MethodDelegateCommand(PlayersResetMute),
                            Selected = true,
                        }
                    }
                    ;
                    else
                    {
                        item = new ListItem(Consts.KEY_NAME, Consts.RES_MUTE)
                        {
                            Command = new MethodDelegateCommand(PlayersMute)
                        }
                    };
                    item.AdditionalProperties[Consts.KEY_NAVIGATION_MODE] = NavigationMode.ExitPCWorkflow;
                    _playerSlotAudioMenu.Add(item);
                }

                IList <IPlayerContext> playerContexts = playerContextManager.PlayerContexts.ToList();
                _playerSlotAudioMenu.FireChange();
                _playerSlotAudioMenuHeader = LocalizationHelper.CreateResourceString(Consts.RES_PLAYER_SLOT_AUDIO_MENU).Evaluate(
                    GetNameForPlayerContext(_playerAudioMenuPlayerContext, playerContexts.IndexOf(_playerAudioMenuPlayerContext)));
            }
        }
示例#15
0
        async Task <MediaStreamSource> createMediaStream2(string url = "ms-appx:///Assets/test.mp3")
        {
            var file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(new Uri(url));

            var stream = await file.OpenReadAsync();

            MusicProperties mp3FileProperties = await file.Properties.GetMusicPropertiesAsync();


            List <string> encodingPropertiesToRetrieve = new List <string>();

            encodingPropertiesToRetrieve.Add("System.Audio.SampleRate");
            encodingPropertiesToRetrieve.Add("System.Audio.ChannelCount");
            encodingPropertiesToRetrieve.Add("System.Audio.EncodingBitrate");
            var encodingProperties = await file.Properties.RetrievePropertiesAsync(encodingPropertiesToRetrieve);

            uint sampleRate   = (uint)encodingProperties["System.Audio.SampleRate"];
            uint channelCount = (uint)encodingProperties["System.Audio.ChannelCount"];
            uint bitRate      = (uint)encodingProperties["System.Audio.EncodingBitrate"];

            /*
             * 44100 2 128000
             * 44100 2 171896   music: 00:03:33.2114285
             * 44100 2 130000   music: 00:00:30.0930000
             * SampleRate/SamplesPerSec
             *    Stereo/Channels
             *       SR*SO*SS/BA
             *
             * 130.3 16  2
             * DataRate
             *   SampleSize/BitsPerSample
             *        BlockAlign
             */
            // var audiodesc = new AudioStreamDescriptor(AudioEncodingProperties.CreateMp3(44100, 2, 128000));
            var audiodesc = new AudioStreamDescriptor(AudioEncodingProperties.CreateMp3(sampleRate, channelCount, bitRate));
            var c         = new MediaStreamSource(audiodesc);

            c.Duration = mp3FileProperties.Duration;
            c.CanSeek  = true;

            Debug.WriteLine("music: " + c.Duration);
            Debug.WriteLine(mp3FileProperties.Title + "  " + sampleRate + " " + channelCount + " " + bitRate);



            UInt32   sampleSize     = 300;                          //每一段
            TimeSpan sampleDuration = new TimeSpan(0, 0, 0, 0, 70); //每一段进度条移动距离
            ulong    byteOffset     = 0;
            TimeSpan timeOffset     = new TimeSpan(0);

            c.Starting += (s, e) => {
                Debug.WriteLine("==Starting==");
                MediaStreamSourceStartingRequest request = e.Request;
                if ((request.StartPosition != null) && request.StartPosition.Value <= c.Duration)
                {
                    UInt64 sampleOffset = (UInt64)request.StartPosition.Value.Ticks / (UInt64)sampleDuration.Ticks;
                    timeOffset = new TimeSpan((long)sampleOffset * sampleDuration.Ticks);
                    byteOffset = sampleOffset * sampleSize;
                }
                request.SetActualStartPosition(timeOffset);
            };
            c.SampleRequested += async(s, e) => {
                //Debug.WriteLine(timeOffset);
                var deferal = e.Request.GetDeferral();
                if (byteOffset + sampleSize <= stream.Size)
                {
                    Debug.WriteLine(sampleSize + "    " + timeOffset);
                    var sample = await MediaStreamSample.CreateFromStreamAsync(stream.GetInputStreamAt(byteOffset), sampleSize, timeOffset); //每一段的数据大小

                    sample.Duration  = sampleDuration;                                                                                       //每一段进度条移动距离
                    sample.KeyFrame  = true;
                    e.Request.Sample = sample;
                    byteOffset      += sampleSize;
                    timeOffset       = timeOffset.Add(sampleDuration);
                }
                deferal.Complete();
            };
            return(c);
        }
示例#16
0
        private void OnDownloadProgessStarted(object sender, EventArgs e)
        {
            // initialize Parsing Variables
            this.m_byteOffset = 0;
            this.m_timeOffset = new TimeSpan(0);

            if (this.m_audioStreamDownloader.TotalBytesToReceive > 0)
            {
                var stream = this.m_audioStreamDownloader.Stream;
                MpegFrame mpegFrame = stream.ReadPastId3V2Tags();

                AudioEncodingProperties audioProps = AudioEncodingProperties.CreateMp3((uint)mpegFrame.SamplingRate, 2, (uint)mpegFrame.Bitrate);
                AudioStreamDescriptor audioDescriptor = new AudioStreamDescriptor(audioProps);

                //close the MediaStreamSource and remove the MediaStreamSource event handlers
                CloseMediaStreamSource(this.m_mediaStreamSource);

                this.m_mediaStreamSource = new Windows.Media.Core.MediaStreamSource(audioDescriptor);
                this.m_mediaStreamSource.CanSeek = true;
                this.m_mediaStreamSource.Duration = this.m_currentTrack.Duration;

                // hooking up the MediaStreamSource event handlers 
                this.m_mediaStreamSource.Starting += OnStreamSourceStarting;
                this.m_mediaStreamSource.SampleRequested += OnStreamSourceSampleRequested;
                this.m_mediaStreamSource.Closed += OnStreamSourceClosed;

                this.m_mediaElement.SetMediaStreamSource(this.m_mediaStreamSource);
            }
        }
示例#17
0
        private void OnAudioStarted(object sender, NetStreamAudioStartedEventArgs args)
        {
            if (_IsClosed)
            {
                throw new Exception();
            }
            if (_Connection == null)
            {
                Debug.WriteLine("すでに閉じられたRTMP接続です");
                return;
            }
            if (isAlreadHaveAudio)
            {
                return;
            }

            var info = args.Info;
            AudioEncodingProperties prop;

            if (info.Format == Mntone.Rtmp.Media.AudioFormat.Mp3)
            {
                prop = AudioEncodingProperties.CreateMp3(info.SampleRate, info.ChannelCount, info.Bitrate);
            }
            else if (info.Format == Mntone.Rtmp.Media.AudioFormat.Aac)
            {
                prop = AudioEncodingProperties.CreateAac(info.SampleRate, info.ChannelCount, info.Bitrate);
            }
            else
            {
                if (_MediaStreamSource != null)
                {
                    Started?.Invoke(new NicovideoRtmpClientStartedEventArgs(_MediaStreamSource));
                }
                return;
            }

            prop.BitsPerSample = info.BitsPerSample;

            var desc = new AudioStreamDescriptor(prop);

            if (_MediaStreamSource != null)
            {
                try
                {
                    _MediaStreamSource.AddStreamDescriptor(desc);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                }

                Started?.Invoke(new NicovideoRtmpClientStartedEventArgs(_MediaStreamSource));
            }
            else
            {
                CreateMediaStream(desc);
                if (args.AudioOnly)
                {
                    Started?.Invoke(new NicovideoRtmpClientStartedEventArgs(_MediaStreamSource));
                }
            }

            isAlreadHaveAudio = true;

            Debug.WriteLine($"{nameof(NicovideoRtmpClient)}: audio : id:{ClientId}");
        }
示例#18
0
        public virtual MediaStreamSource OpenSource()
        {
            var descriptor = new AudioStreamDescriptor(EncodingProperties);

            var mss = new MediaStreamSource(descriptor);

            mss.Starting += MssOnStarting;
            mss.SampleRequested += MssOnSampleRequested;
            mss.Closed += MssOnClosed;

            return mss;
        }
        async private void InitializeMediaStreamSource()
        {
            // initialize Parsing Variables
            byteOffset = 0;
            timeOffset = new TimeSpan(0);

            // get the encoding properties of the input MP3 file

            List<string> encodingPropertiesToRetrieve = new List<string>();

            encodingPropertiesToRetrieve.Add("System.Audio.SampleRate");
            encodingPropertiesToRetrieve.Add("System.Audio.ChannelCount");
            encodingPropertiesToRetrieve.Add("System.Audio.EncodingBitrate");

            IDictionary<string, object> encodingProperties = await inputMP3File.Properties.RetrievePropertiesAsync(encodingPropertiesToRetrieve);

            uint sampleRate = (uint)encodingProperties["System.Audio.SampleRate"];
            uint channelCount = (uint)encodingProperties["System.Audio.ChannelCount"];
            uint bitRate = (uint)encodingProperties["System.Audio.EncodingBitrate"];

            // get the common music properties of the input MP3 file

            MusicProperties mp3FileProperties = await inputMP3File.Properties.GetMusicPropertiesAsync();
            songDuration = mp3FileProperties.Duration;

            // creating the AudioEncodingProperties for the MP3 file

            AudioEncodingProperties audioProps = AudioEncodingProperties.CreateMp3(sampleRate, channelCount, bitRate);

            // creating the AudioStreamDescriptor for the MP3 file
 
            AudioStreamDescriptor audioDescriptor = new AudioStreamDescriptor(audioProps);

            // creating the MediaStreamSource for the MP3 file

            MSS = new Windows.Media.Core.MediaStreamSource(audioDescriptor);
            MSS.CanSeek = true;
            MSS.MusicProperties.Title = mp3FileProperties.Title;
            MSS.Duration = songDuration;

            // hooking up the MediaStreamSource event handlers
            MSS.Starting += MSS_Starting;
            MSS.SampleRequested += MSS_SampleRequested;
            MSS.Closed += MSS_Closed;

            mediaPlayer.SetMediaStreamSource(MSS);
            rootPage.NotifyUser("MediaStreamSource created and set as source", NotifyType.StatusMessage);
        }