CSCore - 从 FileStream 或 MemoryStream 播放音频

Boh*_*hoo 5 audio cscore

使用 CSCore,如何从FileStreamor播放 WMA 或 MP3 MemoryStream(与使用string文件路径或 url的方法不同)。

Dom*_* B. 5

由于GetCodec(Stream stream, object key)该的-过载CodecFactory-class是内部的,你可以简单地手动执行相同的步骤,直接选择您的解码器。实际上,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);

}
Run Code Online (Sandbox Code Playgroud)

对于 WMA,您可以使用WmaDecoder。您应该检查不同解码器的实现:https : //github.com/filoe/cscore/blob/master/CSCore/Codecs/CodecFactory.cs#L30

确保没有抛出异常,并像链接的源代码一样使用另一个解码器 ( Mp3MediafoundationDecoder )处理它们。也不要忘记最后处理你的流。