Can I play a video using MediaPlayerElement with System.IO.Stream?

  • Thread starter Thread starter Erantha Welikala
  • Start date Start date
E

Erantha Welikala

Guest
Below code snippet shows what I have done to receive a stream which was sent by a WebSocketServer. Here what I am doing is, waiting until the whole byte array comes in and write the byte array to a file and loads the video as the source of the MediaPlayerElement. So with this implementation I have to wait until the whole video received.

Do I have a way to play the video while it is receiving?

Just converting the stream into IRandomAccessStream doesn't solve the issue.

mediaPlayerElement.Source = MediaSource.CreateFromStream(readStream.AsRandomAccessStream(), ".mpeg");

It throws an error saying "Cannot use the specified Stream as a Windows Runtime IRandomAccessStream because this Stream does not support seeking."

Can anyone suggest me a solution?



private async Task ReceiveDataAsync(StreamWebSocket activeSocket)
{
Stream readStream = streamWebSocket.InputStream.AsStreamForRead();
int bytesReceived = 0;
try
{
byte[] readBuffer = new byte[FILE_SIZE];
byte[] buffer = new byte[FILE_SIZE];
while (true)
{
if (streamWebSocket != activeSocket)
{
// Our socket is no longer active. Stop reading.
AppendOutputLine("Background read stopped.");
return;
}

int read = await readStream.ReadAsync(readBuffer, 0, readBuffer.Length);
for (int i = bytesReceived; i < bytesReceived + read; i++)
{
buffer = readBuffer[i - bytesReceived];
}
bytesReceived += read;
if(bytesReceived==FILE_SIZE)
{
StorageFile newFile = await KnownFolders.PicturesLibrary.CreateFileAsync(OUTPUTFILENAME,
CreationCollisionOption.GenerateUniqueName);
await FileIO.WriteBytesAsync(newFile, buffer);
mediaPlayerElement.Source = MediaSource.CreateFromStorageFile(newFile);
}
DataReceivedField.Text = bytesReceived.ToString();
}
}
catch (Exception ex)
{
WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult);

switch (status)
{
case WebErrorStatus.OperationCanceled:
AppendOutputLine("Background read canceled.");
break;

default:
AppendOutputLine("Error: " + status);
AppendOutputLine(ex.Message);
break;
}
}
}

Continue reading...
 
Back
Top