我正在使用MediaPlayerElement创建Twitch播放器,我想实时更新MediaPlayerElement的缓冲区,但是我不知道如何。
我试图这样做:
public sealed partial class MainPage : Page
{
MemoryStream stream = new MemoryStream(64 * 1024 * 1024);
BinaryWriter writer;
BinaryReader reader;
Task task;
public MainPage()
{
this.InitializeComponent();
writer = new BinaryWriter(stream);
}
async void ReadTask()
{
while (true)
{
var bytes = reader.ReadBytes(1024 * 1024);
if (bytes.Length == 0)
{
break;
}
writer.Write(bytes);
// Do some delay to see progress of loading
await Task.Delay(1000);
}
}
private async void Page_Loaded(object sender, RoutedEventArgs e)
{
// I'm using file to speed up tests
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/output.ts"));
reader = new BinaryReader(await file.OpenStreamForReadAsync());
// Write few first bytes
writer.Write(reader.ReadBytes(1024 * 1024));
// Start task which will write more bytes soon
task = new Task(ReadTask);
task.Start();
StreamMediaPlayer.AreTransportControlsEnabled = true;
StreamMediaPlayer.AutoPlay = true;
StreamMediaPlayer.MediaPlayer.Volume = 0;
StreamMediaPlayer.Source = MediaSource.CreateFromStream(writer.BaseStream.AsRandomAccessStream(), "video/MP2T");
}
}
此代码有效,但即使TaskRead()
在播放视频时写入更多字节,播放器也只会显示我在设置源之前写入的前1 MB。
我还尝试使用方法CreateFromStreamReference
代替CreateFromStream
,如下所示:
var s = RandomAccessStreamReference.CreateFromStream(writer.BaseStream.AsRandomAccessStream());
StreamMediaPlayer.Source = MediaSource.CreateFromStreamReference(s, "video/MP2T");
但这根本不起作用。
这是一个包含视频的完整项目:https://drive.google.com/open?id=175Z5HzK3MJ-Dm4ZX84r81lWYtZ0ahSSS
答案 0 :(得分:0)
我知道了。
我必须使用MseStreamSource
。
首先,我需要使用以下事件创建MseStreamSource
:
streamSource = new MseStreamSource();
streamSource.Opened += (_, __) =>
{
if (buffer is null)
{
// it will create buffer where I can write data
buffer = streamSource.AddSourceBuffer("video/MP2T");
buffer.Mode = MseAppendMode.Sequence;
}
};
然后设置源:
StreamMediaPlayer.Source = MediaSource.CreateFromMseStreamSource(streamSource);
如果我想添加视频,我必须这样做:
buffer.AppendBuffer(reader.ReadBytes(20 * 1024 * 1024).AsBuffer());
我必须确保缓冲区没有更新。此信息提供IsUpdating
属性。