如何播放需要身份验证的视频流?

Tho*_*que 3 c# authentication video-streaming windows-runtime windows-store-apps

我有一个Windows应用程序(C#/ XAML),它与REST服务进行通信.在某些时候,我需要播放此服务提供的视频流.

如果我只是将流URI分配给MediaElement.Source属性,它就不起作用,因为需要对请求进行身份验证.我需要定制通过发送请求MediaElement控制,以增加饼干,凭证和其他一些自定义页眉,但我找不到任何方法或属性做到这一点.

我该怎么做?它甚至可能吗?

Tho*_*que 6

好的,我搞定了.基本上,解决方案有两个部分:

  • 手动发出HTTP请求(使用任何所需的凭据或标头)
  • 将响应流包装在一个自定义中IRandomAccessStream,Seek通过向服务器发出另一个请求来实现,使用Range标头指定我需要的流的哪个部分.

这是RandomAccessStream实施:

delegate Task<Stream> AsyncRangeDownloader(ulong start, ulong? end);

class StreamingRandomAccessStream : IRandomAccessStream
{
    private readonly AsyncRangeDownloader _downloader;
    private readonly ulong _size;

    public StreamingRandomAccessStream(Stream startStream, AsyncRangeDownloader downloader, ulong size)
    {
        if (startStream != null)
            _stream = startStream.AsInputStream();
        _downloader = downloader;
        _size = size;
    }

    private IInputStream _stream;
    private ulong _requestedPosition;

    public void Dispose()
    {
        if (_stream != null)
            _stream.Dispose();
    }

    public IAsyncOperationWithProgress<IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options)
    {
        return AsyncInfo.Run<IBuffer, uint>(async (cancellationToken, progress) =>
        {
            progress.Report(0);
            if (_stream == null)
            {
                var netStream = await _downloader(_requestedPosition, null);
                _stream = netStream.AsInputStream();
            }
            var result = await _stream.ReadAsync(buffer, count, options).AsTask(cancellationToken, progress);
            return result;
        });
    }

    public void Seek(ulong position)
    {
        if (_stream != null)
            _stream.Dispose();
        _requestedPosition = position;
        _stream = null;
    }

    public bool CanRead { get { return true; } }
    public bool CanWrite { get { return false; } }
    public ulong Size { get { return _size; } set { throw new NotSupportedException(); } }

    public IAsyncOperationWithProgress<uint, uint> WriteAsync(IBuffer buffer) { throw new NotSupportedException(); }
    public IAsyncOperation<bool> FlushAsync() { throw new NotSupportedException(); }
    public IInputStream GetInputStreamAt(ulong position) { throw new NotSupportedException(); }
    public IOutputStream GetOutputStreamAt(ulong position) { throw new NotSupportedException(); }
    public IRandomAccessStream CloneStream() { throw new NotSupportedException(); }
    public ulong Position { get { throw new NotSupportedException(); } }
}
Run Code Online (Sandbox Code Playgroud)

它可以像这样使用:

private HttpClient _client;
private void InitClient()
{
    _client = new HttpClient();
    // Configure the client as needed with CookieContainer, Credentials, etc
    // ...
}

private async Task StartVideoStreamingAsync(Uri uri)
{
    var request = new HttpRequestMessage(HttpMethod.Get, uri);
    // Add required headers
    // ...

    var response = await _client.SendAsync(request);
    ulong length = (ulong)response.Content.Headers.ContentLength;
    string mimeType = response.Content.Headers.ContentType.MediaType;
    Stream responseStream = await response.Content.ReadAsStreamAsync();

    // Delegate that will fetch a stream for the specified range
    AsyncRangeDownloader downloader = async (start, end) =>
        {
            var request2 = new HttpRequestMessage();
            request2.Headers.Range = new RangeHeaderValue((long?)start, (long?)end);
            // Add other required headers
            // ...
            var response2 = await _client.SendAsync(request2);
            return await response2.Content.ReadAsStreamAsync();
        };

    var videoStream = new StreamingRandomAccessStream(responseStream, downloader, length);
    _mediaElement.SetSource(videoStream, mimeType);
}
Run Code Online (Sandbox Code Playgroud)

用户可以寻找视频中的任意位置,并且流将发出另一个请求以使流在指定位置.

它仍然比我想象的要复杂,但它有效......

请注意,服务器必须支持Range请求中的标头,并且必须Content-Length在初始响应中发出标头.