Question

Is it possible to cut an audio file using CSCore-Library? For example I want to start a mp3 on second 20 and stop it on second 50 and I want to generate a new mp3 file, which does that.

Was it helpful?

Solution

There are two ways to cut a mp3 file.

  1. Parse the mp3 file to get all mp3 frames. Copy the frames you don't want to be cut out and paste them into a new stream.
  2. Decode the whole mp3 file and re-encode the data you don't want to be cut out.

The first method has the disadvantages that it is more complicated than method 2 and that you can't cut the mp3 precisely. That means, that you are restricted to the size of the mp3 frames.

The second method would be exactly what you are looking for. But there is one big problem: MP3-encoding is only supported since Windows 8. That means that you can't use this method in Windows XP, Vista or Windows 7.

--> I would recommend you to use any third-party components like lame, ffmpeg,...

Anyway... an example for method 2:

private static void Main(string[] args)
{
    TimeSpan startTimeSpan = TimeSpan.FromSeconds(20);
    TimeSpan endTimeSpan = TimeSpan.FromSeconds(50);

    using (IWaveSource source = CodecFactory.Instance.GetCodec(@"C:\Temp\test.mp3"))
    using (MediaFoundationEncoder mediaFoundationEncoder =
        MediaFoundationEncoder.CreateWMAEncoder(source.WaveFormat, @"C:\Temp\dest0.mp3"))
    {
        AddTimeSpan(source, mediaFoundationEncoder, startTimeSpan, endTimeSpan);
    }
}

private static void AddTimeSpan(IWaveSource source, MediaFoundationEncoder mediaFoundationEncoder, TimeSpan startTimeSpan, TimeSpan endTimeSpan)
{
    source.SetPosition(startTimeSpan);

    int read = 0;
    long bytesToEncode = source.GetBytes(endTimeSpan - startTimeSpan);

    var buffer = new byte[source.WaveFormat.BytesPerSecond];
    while ((read = source.Read(buffer, 0, buffer.Length)) > 0)
    {
        int bytesToWrite = (int)Math.Min(read, bytesToEncode);
        mediaFoundationEncoder.Write(buffer, 0, bytesToWrite);
        bytesToEncode -= bytesToWrite;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top