【发布时间】:2016-09-16 23:14:10
【问题描述】:
使用 CSCore,我如何从 FileStream 或 MemoryStream 播放 WMA 或 MP3(与使用 string 作为文件路径或 URL 的方法不同)。
【问题讨论】:
使用 CSCore,我如何从 FileStream 或 MemoryStream 播放 WMA 或 MP3(与使用 string 作为文件路径或 URL 的方法不同)。
【问题讨论】:
由于CodecFactory-class 的GetCodec(Stream stream, object key)-overload 是内部的,您可以简单地手动执行相同的步骤并直接选择您的解码器。实际上,CodeFactory 只是一个帮助类,用于自动确定解码器,所以如果你已经知道你的编解码器,你可以自己做。
在内部,当传递一个文件路径时,CSCore 检查文件扩展名,然后打开一个FileStream(使用File.OpenRead),它会被处理到所选的解码器。
您需要做的就是为您的编解码器使用特定的解码器。
对于 MP3,您可以使用继承自 DmoStream 的 DmoMP3Decoder,它实现了您需要作为声源处理的 IWaveSource 接口。
这是来自Codeplex 文档的调整示例:
public void PlayASound(Stream stream)
{
//Contains the sound to play
using (IWaveSource soundSource = GetSoundSource(stream))
{
//SoundOut implementation which plays the sound
using (ISoundOut soundOut = GetSoundOut())
{
//Tell the SoundOut which sound it has to play
soundOut.Initialize(soundSource);
//Play the sound
soundOut.Play();
Thread.Sleep(2000);
//Stop the playback
soundOut.Stop();
}
}
}
private ISoundOut GetSoundOut()
{
if (WasapiOut.IsSupportedOnCurrentPlatform)
return new WasapiOut();
else
return new DirectSoundOut();
}
private IWaveSource GetSoundSource(Stream stream)
{
// Instead of using the CodecFactory as helper, you specify the decoder directly:
return new DmoMp3Decoder(stream);
}
对于 WMA,您可以使用 WmaDecoder。 您应该检查不同解码器的实现:https://github.com/filoe/cscore/blob/master/CSCore/Codecs/CodecFactory.cs#L30
确保没有抛出异常,并使用链接源代码中的另一个解码器 (Mp3MediafoundationDecoder) 来处理它们。也不要忘记在最后处理你的流。
【讨论】: