簡體   English   中英

如何同時讀取和寫入流以在Silverlight 4 MediaStreamSource中播放媒體文件?

[英]How do I simultaneously read and write to a stream for playing media file in Silverlight 4 MediaStreamSource?

背景

我有一個媒體文件,正在使用WebClient.OpenReadAsync / OpenReadCompleted和Stream.BeginRead / AsyncCallback逐步下載到Silverlight 4應用程序。 目的是通過調用SetSource方法在MediaElement中播放文件,傳入我們自定義MediaStreamSource的實例,以便在下載文件的所有內容之前可以開始播放文件。 媒體文件使用自定義編碼/解碼,這就是為什么我們使用自定義MediaStreamSource的原因。 我們的MediaStreamSource可以接受Stream,並開始解析軌道信息並在MediaElement中播放。 我已經確認我正在逐步下載文件內容。 以下是下載代碼的摘要:

public void SetSource(string sourceUrl)
{
    var uriBuilder = new UriBuilder(sourceUrl);
    WebClient webClient = new WebClient();

    // AllowReadStreamBuffering = false allows us to get the stream
    // before it's finished writing to it.
    webClient.AllowReadStreamBuffering = false;
    webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
    webClient.OpenReadAsync(uriBuilder.Uri);
}

void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    _inboundVideoStream = e.Result;
    BeginReadingFromStream();
}

private void BeginReadingFromStream()
{
    if (_inboundVideoStream.CanRead)
    {
        _chunk = new byte[_chunkSize];
        _inboundVideoStream.BeginRead(_chunk, 0, _chunk.Length, new AsyncCallback(BeginReadCallback), _inboundVideoStream);
    }
}

private void BeginReadCallback(IAsyncResult asyncResult)
{
    Stream stream = asyncResult.AsyncState as Stream;
    int bytesRead = stream.EndRead(asyncResult);
    _totalBytesRead += bytesRead;

    if (_playableStream == null)
        _playableStream = new MemoryStream();

    _playableStream.Write(_chunk, 0, _chunk.Length);

    if (!_initializedMediaStream && _playableStream.Length >= _minimumToStartPlayback)
    {
        _initializedMediaStream = true;

        // Problem: we can't hand the stream source a stream that's still being written to
        // It's Position is at the end.  Can I read and write from the same stream or is there another way
        MP4MediaStreamSource streamSource = new MP4MediaStreamSource(_playableStream);

        this.Dispatcher.BeginInvoke(() =>
        {
            mediaElement1.SetSource(streamSource);
        });
    }

    if (_totalBytesRead < _fileSize)
    {
        ReadFromDownloadStream();
    }
    else
    {
        // Finished downloading
    }
}

我已經嘗試過同時寫入/讀取MemoryStream(如上所述),以及寫入IsolatedStorageFile並在寫入文件時讀取該文件。 到目前為止,我還沒有找到使這兩種方法都能起作用的方法。

題:

有沒有辦法讀取和寫入相同的流? 還是有使用流和MediaStreamSource實現此目的的標准方法?

謝謝

我在MediaStreamSource實現中執行此操作的方式是在其中包含2個流:一個用於讀取,一個用於寫入。

每次調用GetSampleAsync()時,我都會使用寫入流的緩沖區來處理並重新創建讀取流。 我猜想的另一種方法是,在創建MediaStreamSample傳遞給ReportGetSampleCompleted()時使用負偏移,因為流的位置始終在末尾,但是您必須確保該位置在末尾這將不起作用,為了簡單起見,我只使用了2個流

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM