Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# : concatenate 2 MP3 files

Tags:

c#

merge

concat

mp3

I tried to concatenate 2 MP3 files using the code below. I got a new file which I can play the first half of (complete first file), but the second half is silent. The length of the new file was correct. What do I do wrong?

List<Byte[]> files = new List<byte[]>();
var tempfile = File.ReadAllBytes(Path.Combine(path, "1.mp3"));
files.Add(tempfile);
tempfile = File.ReadAllBytes(Path.Combine(path, "2.mp3"));
files.Add(tempfile);
Byte[] a=new Byte[files[0].Length+files[1].Length];
Array.Copy(files[0], a, files[0].Length);
Array.Copy(files[1], a, files[1].Length);

File.WriteAllBytes(Path.Combine(path, "3.mp3") , a);
like image 852
Markus Avatar asked Sep 21 '09 17:09

Markus


Video Answer


3 Answers

Simple:

public static void Combine(string[] mp3Files, string mp3OuputFile)
{
    using (var w = new  BinaryWriter(File.Create(mp3OuputFile)))
    {
        new List<string>(mp3Files).ForEach(f => w.Write(File.ReadAllBytes(f)));
    }
}
like image 185
Sith2021 Avatar answered Sep 29 '22 04:09

Sith2021


I am willing to bet you are only hearing the second song. (and that either both files are the same length or the first is shorter)

You are copying the second song data over the first. And MP3 data is streaming so you can just append the files to each other without worrying about bitrates (while they may glitch) the bitrate should automaticly adjust.

Detail on MP3 Frame headers

... try this...

Array.Copy(files[0], 0, a, 0, files[0].Length);
Array.Copy(files[1], 0, a, files[0].Length, files[1].Length);

... or better still...

using (var fs = File.OpenWrite(Path.Combine(path, "3.mp3")))
{
    var buffer = File.ReadAllBytes(Path.Combine(path, "1.mp3"));
    fs.Write(buffer, 0, buffer.Length);
    buffer = File.ReadAllBytes(Path.Combine(path, "2.mp3"));
    fs.Write(buffer, 0, buffer.Length);
    fs.Flush();
}
like image 33
Matthew Whited Avatar answered Sep 29 '22 04:09

Matthew Whited


This question has been asked before here and here. Also see reading MP3 Headers in C#, but instead of reading the header you just want to strip it off, concatenate the rest, then generate a new header for the concatenated file.

Edit: After further reading apparently it doesn't make any difference if you just concatenate the files without stripping the ID3 tags. But it still seems like a good idea to strip them out first.

like image 44
Dale Avatar answered Sep 29 '22 04:09

Dale