Today, when I was working on a project, I encountered how to bind the audio stream in the byte [] array to the mediaelement control. There is a method in the mediaelement control.
Public void setsource (irandomaccessstream stream, string mimetype); this method binds the audio to the mediaelement control as a stream to play the audio file.
Now the problem is that we can change the audio stream in the byte [] array to the memorystream type. But how can we change the stream of the memorystream type to the irandomaccessstream type?
Next we will implement it step by step:
1. First, convert byte [] to a memorystream type
Memorystream stream = new memorystream (BIT) // byte array whose bit is of the byte [] Type
2. Then we convert the memorystream type to the irandomaccessstream type
Private async task <irandomaccessstream> convert (memorystream Stream)
{
VaR randomaccessstream = new inmemoryrandomaccessstream ();
VaR outputstream = randomaccessstream. getoutputstreamat (0 );
VaR DW = new datawriter (outputstream );
VaR task = new task () => DW. writebytes (stream. toarray ()));
Task. Start ();
Await task;
Await DW. storeasync ();
VaR success = await outputstream. flushasync ();
Return randomaccessstream;
}
3. Finally, bind the stream converted to irandomaccessstream to the audio control to play the audio file.
Mediaelement. setsource (stream ,"");
The preceding figure shows how to flow byte [] bytes to the irandomaccessstream stream.
There are also some conversions between streams:
1. stream to byte []
Public static byte [] convertstreamtobyte (Stream Input)
{
Byte [] buffer = new byte [16*1024];
Using (memorystream MS = new memorystream ())
{
Int read;
While (read = input. Read (buffer, 0, buffer. Length)> 0)
{
Ms. Write (buffer, 0, read );
}
Return Ms. toarray ();
}
}
2. stream to memorystream
Public static memorystream convertstreamtomemorystream (Stream)
{
Memorystream = new memorystream ();
If (stream! = NULL)
{
Byte [] buffer = readfully (Stream );
If (buffer! = NULL)
{
VaR binarywriter = new binarywriter (memorystream );
Binarywriter. Write (buffer );
}
}
Return memorystream;
}
3. Convert string to ibuffer
Private ibuffer convert (string text)
{
Using (inmemoryrandomaccessstream stream = new inmemoryrandomaccessstream ())
{
Using (datawriter = new datawriter ())
{
Datawriter. writestring (text );
Return datawriter. detachbuffer ();
}
}
}
For more detailed conversions, see http://www.cnblogs.com/jing870812/archive/2012/04/12/2444870.html