使用Naudio lib播放.wav文件

时间:2012-04-02 16:19:07

标签: c# .net audio naudio

我尝试打开并使用NAudio lib播放.wav个文件。

private OpenFileDialog openFileDialog = null;
private NAudio.Wave.IWavePlayer waveOutDevice;
private NAudio.Wave.BlockAlignReductionStream reductionStream = null;

private NAudio.Wave.BlockAlignReductionStream CreateStream(OpenFileDialog fileDialog)
{

    if (fileDialog.FileName.EndsWith(".mp3"))
    {
        NAudio.Wave.WaveStream pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(fileDialog.FileName));
        reductionStream = new NAudio.Wave.BlockAlignReductionStream(pcm);
    }
    else if (fileDialog.FileName.EndsWith(".wav"))
    {
        NAudio.Wave.WaveStream pcm = new NAudio.Wave.WaveChannel32(new NAudio.Wave.WaveFileReader(openFileDialog.FileName));
        reductionStream = new NAudio.Wave.BlockAlignReductionStream(pcm);
    }
    else
    {
        throw new InvalidOperationException("Unsupported");
    }

    return reductionStream;
}

并在播放按钮中:

waveOutDevice = new NAudio.Wave.DirectSoundOut();
reductionStream = CreateStream(openFileDialog);
waveOutDevice.Init(reductionStream);

我正在使用NAudio 1.5版本。对于mp3文件,这很好玩。当我选择.wav时,播放缓慢,吱吱作响。 WaveStream可能有问题pcm = WaveChannel32

1 个答案:

答案 0 :(得分:4)

您不需要使用BlockAlignReductionStream,WaveChannel32或CreatePcmStream。只需使用Mp3FileReader或WaveFileReader并将其传递给您的IWavePlayer,