SoFunction
Updated on 2025-04-14

Complete guide to audio processing using C# (from play to editing)

1. C# audio playback: basic operation

Audio playback is a basic function of audio processing. In C#, audio playback can be done through a built-in class library, such as for playing WAV files, used to play audio files in multiple formats.

Play WAV files using SoundPlayer

using System;
using ;
 
class Program
{
    static void Main()
    {
        // Create a SoundPlayer instance and load the WAV file        SoundPlayer player = new SoundPlayer("");
        
        // Asynchronously play audio        ();
        
        // Synchronously play audio (the program will wait for the audio to be played back and continue to execute)        ();
    }
}

Play MP3 files using MediaElement (WPF application)

For audio in MP3 and other formats,MediaElementControls are a great choice. It supports playing multiple audio formats in WPF applications.

using System;
using ;
 
class Program
{
    static void Main()
    {
        MediaElement mediaElement = new MediaElement();
         = new Uri("example.mp3");
        ();
    }
}

2. C# Audio Recording: How to Capture Sound

Audio recording is often used in scenes such as voice recognition, conference recording, and sound annotation. In C#, we usually use open source librariesNAudioto perform audio recording.

Install the NAudio library

Installation via NuGet in Visual StudioNAudio

Install-Package NAudio

Record audio using NAudio and save as WAV file

The following example shows how to use itNAudioLibrary record audio and save it to a file:

using System;
using ;
 
class Program
{
    static void Main()
    {
        string outputFile = "recorded_audio.wav";
        
        // Create a WaveInEvent object to capture audio data        using (WaveInEvent waveIn = new WaveInEvent())
        {
             = new WaveFormat(44100, 1);  // Set the sampling rate and number of channels             += (sender, e) =>
            {
                using (WaveFileWriter writer = new WaveFileWriter(outputFile, ))
                {
                    (, 0, );  // Write audio data                }
            };
 
            // Start recording            ();
            ("Press any key to stop recording...");
            ();
            ();
        }
 
        ("Recording stopped and saved.");
    }
}

3. C# audio editing: processing and modifying audio files

Audio editing includes modifying the volume, frequency, editing, merging, etc. of the audio. In C#,NAudioThe library can also be used to process and edit audio files.

Adjust the volume

useNAudioofVolumeSampleProviderThe audio volume can be adjusted.

using System;
using ;
using ;
 
class Program
{
    static void Main()
    {
        string inputFile = "";
        string outputFile = "output_with_volume.wav";
 
        using (var reader = new AudioFileReader(inputFile))
        {
            // Set volume adjustment            var volumeProvider = new VolumeSampleProvider(reader);
             = 0.5f;  // Set the volume to 50% 
            using (var writer = new WaveFileWriter(outputFile, ))
            {
                byte[] buffer = new byte[];
                int bytesRead;
                while ((bytesRead = (buffer, 0, )) > 0)
                {
                    (buffer, 0, bytesRead);  // Write the modified audio                }
            }
        }
 
        ("Audio processed and saved.");
    }
}

Crop audio

Cropping audio is a common audio editing operation. You can useNAudioTo read the audio data and edit it into a specified time period.

using System;
using ;
 
class Program
{
    static void Main()
    {
        string inputFile = "";
        string outputFile = "cropped_audio.wav";
 
        using (var reader = new WaveFileReader(inputFile))
        {
            // Set the start and end time of audio clipping (seconds)            var startSample = (int)(10 * );
            var endSample = (int)(20 * );
            var totalSamples = (int)(endSample - startSample);
 
            using (var writer = new WaveFileWriter(outputFile, ))
            {
                (startSample * , );
 
                byte[] buffer = new byte[totalSamples * ];
                int bytesRead;
                while ((bytesRead = (buffer, 0, )) > 0)
                {
                    (buffer, 0, bytesRead);
                }
            }
        }
 
        ("Audio cropped and saved.");
    }
}

4. Audio format conversion: WAV and MP3 conversion

In many application scenarios, we may need to convert audio files from one format to another. For example, convert a WAV file to an MP3 file. passlibrary, you can easily implement this format conversion.

Install

Install-Package 

Example: Convert WAV file to MP3 file

using System;
using ;
using ;
 
class Program
{
    static void Main()
    {
        string inputWavFile = "";
        string outputMp3File = "output.mp3";
 
        using (var reader = new WaveFileReader(inputWavFile))
        {
            using (var writer = new LameMP3FileWriter(outputMp3File, , LAMEPreset.VBR_90))
            {
                (writer);
            }
        }
 
        ("WAV file has been converted to MP3.");
    }
}

5. Audio Analysis: Spectrum Analysis and FFT

Audio analysis technology is often used in spectrum analysis, sound processing and special effects production. Through FFT (Fast Fourier Transform), we can extract spectrum information of the audio signal.

Spectral Analysis Using NAudio

using System;
using ;
using ;
 
class Program
{
    static void Main()
    {
        string file = "";
        
        using (WaveFileReader reader = new WaveFileReader(file))
        {
            int sampleRate = ;
            int length = (int) / 2;
 
            float[] buffer = new float[length];
            int bytesRead = (buffer, 0, length);
 
            // FFT analysis            Complex[] fftBuffer = new Complex[length];
            for (int i = 0; i < length; i++)
            {
                fftBuffer[i].X = buffer[i];
                fftBuffer[i].Y = 0;
            }
 
            (true, (int)(length, 2), fftBuffer);
 
            // Output frequency data            for (int i = 0; i < length / 2; i++)
            {
                double frequency = (i * sampleRate) / (double)length;
                double magnitude = (fftBuffer[i].X * fftBuffer[i].X + fftBuffer[i].Y * fftBuffer[i].Y);
                ($"Frequency: {frequency} Hz, Magnitude: {magnitude}");
            }
        }
    }
}

6. Summary

In C#, the functions of audio processing are very powerful. Developers can use a variety of libraries and tools to realize audio playback, recording, editing, format conversion and analysis. Commonly used libraries such as NAudio provide developers with rich functions for processing audio files. They can not only perform basic audio playback and recording, but also perform complex audio processing tasks, such as sound effects application, format conversion and spectrum analysis.

With this guide, you can start using C# to build a variety of audio-related applications, including audio players, recording software, sound effects editors, and audio analysis tools.

The above is the detailed content of the complete guide (from playback to editing) for audio processing using C#. For more information about audio processing of C#, please pay attention to my other related articles!