You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用NAudio将PCM 48kHz/16bit单声道WAV转为u-Law格式?

Convert PCM 48kHz 16-bit Mono WAV to u-Law 8kHz 8-bit Mono with NAudio

Alright, let's get your WAV file converted properly using NAudio. Your source specs (PCM 48kHz 16-bit mono) need two key transformations first: downsampling to 8kHz, then converting the encoding to u-Law (which inherently handles the 8-bit depth requirement). Here's a complete, tested code implementation that ties all the pieces together:

using NAudio.Wave;

public void ConvertWavToULaw(string inputFilePath, string outputFilePath)
{
    // Step 1: Read the source PCM WAV file
    using (var reader = new WaveFileReader(inputFilePath))
    {
        // Optional: Validate source format matches your expected specs
        if (reader.WaveFormat.Encoding != WaveFormatEncoding.Pcm ||
            reader.WaveFormat.SampleRate != 48000 ||
            reader.WaveFormat.BitsPerSample != 16 ||
            reader.WaveFormat.Channels != 1)
        {
            throw new InvalidOperationException("Source file doesn't match the expected PCM 48kHz 16-bit mono format.");
        }

        // Step 2: Downsample from 48kHz to 8kHz using Windows DMO resampler
        var resampler = new ResamplerDmoStream(reader, new WaveFormat(8000, 16, 1));

        // Step 3: Convert to u-Law encoding (auto-sets 8-bit, mono, 8kHz)
        var uLawTargetFormat = WaveFormat.CreateMuLawFormat(8000, 1);
        using (var conversionStream = new WaveFormatConversionStream(uLawTargetFormat, resampler))
        {
            // Step 4: Write the final converted u-Law WAV file
            WaveFileWriter.CreateWaveFile(outputFilePath, conversionStream);
        }
    }
}

Key Details to Know:

  • NuGet Setup: Make sure you've installed the NAudio NuGet package—this includes all the stream helpers and format utilities needed here.
  • Resampling Quality: We used ResamplerDmoStream because it leverages Windows' built-in DMO resampler for reliable, quality downsampling. If you prefer, you could swap it for MediaFoundationResampler instead, both work well for this use case.
  • u-Law Format Shortcut: WaveFormat.CreateMuLawFormat(8000, 1) handles all the target format details automatically—u-Law is natively 8-bit, so you don't need to manually set that value.
  • Validation Check: The optional format validation helps catch mismatched source files early, avoiding unexpected conversion errors.

Quick Usage Example:

Call the method with your input and output paths like this:

ConvertWavToULaw(@"C:\audio\source_pcm.wav", @"C:\audio\target_ulaw.wav");

内容的提问来源于stack exchange,提问作者Pleebo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:39:40