Windows Metro 中各种流之间的转换
今天在做项目时,遇到了如何将byte[]数组中的音频流,绑定到MediaElement控件中去,在MediaElement控件中有一个方法
public void SetSource(IRandomAccessStream stream, string mimeType);该方法是将音频以流的方式绑定到MediaElement控件中去,实现音频文件的播放。
现在问题就出现在我们可以将byte[]数组中的音频流转换成MemoryStream类型的流,可是如何将MemoryStream类型的流转换成IRandomAccessStream类型的流呢?
接下来我们一步一步实现:
1.首先先将byte[]转换成MemoryStream类型的
MemoryStream stream = new MemoryStream(bit) //bit为byte[]类型的字节数组
2.然后我们将MemoryStream类型转换成IRandomAccessStream类型的
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.最后将转换成IRandomAccessStream类型的流绑定到音频控件中去,实现音频文件的播放。
MediaElement.SetSource(stream,"");
以上就是实现了如何将Byte[]字节流向IRandomAccessStream流。
另外还有一些流之间的转换:
1.Stream转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转MemoryStream
public static MemoryStream ConvertStreamToMemoryStream(Stream stream)
{
MemoryStream memoryStream = new MemoryStream();
if (stream != null)
{
byte[] buffer = ReadFully(stream);
if (buffer != null)
{
var binaryWriter = new BinaryWriter(memoryStream);
binaryWriter.Write(buffer);
}
}
return memoryStream;
}
3. String 转 IBuffer
private IBuffer Convert(string text)
{
using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
{
using (DataWriter dataWriter = new DataWriter())
{
dataWriter.WriteString(text);
return dataWriter.DetachBuffer();
}
}
}
更详细的转换可参见 http://www.cnblogs.com/jing870812/archive/2012/04/12/2444870.html