我通过简单地添加两个音频样本的字节将两个不同的音频样本混合成一个问题。
在下面的过程中,当我尝试在媒体播放器中打开 mixed.mp3 文件时,它说:
Windows Media Player 在播放文件时遇到问题。
这是我用来混合音频文件的代码:
byte[] bytes1,bytes2,final;
int length1,length2,max;
// Getting byte[] of audio file
using ( BinaryReader b = new BinaryReader(File.Open("background.mp3" , FileMode.Open)) )
{
length1 = (int)b.BaseStream.Length;
bytes1 = b.ReadBytes(length1);
}
using ( BinaryReader b = new BinaryReader(File.Open("voice.mp3" , FileMode.Open)) )
{
length2 = (int)b.BaseStream.Length;
bytes2 = b.ReadBytes(length2);
}
// Getting max length
if(length1 > length2){
max = length1;
}else{
max = length2;
}
// Initializing output byte[] of max length
final = new byte[max];
// Adding byte1 and byte2 and copying into final
for (int i=0;i<max;i++)
{
byte b1 , b2;
if(i < length1){
b1 = bytes1[i];
}else{
b1 = 0;
}
if ( i < length2 ){
b2 = bytes2[i];
}
else{
b2 = 0;
}
final[i] = (byte)(b1 + b2);
}
// Writing final[] as an mp3 file
File.WriteAllBytes("mixed.mp3" , final);
注意:我试图混合两个相同的文件,它工作,也就是说,媒体播放器没有抛出任何错误并正确播放。
1 回答
这很可能是因为在混合之前你不是解码的 MP3 文件。而你只是“将”样本加在一起,这将导致剪裁;您应该首先使用图书馆将 MP3 文件解码为 PCM,然后允许您将它们混合使用。
要正确混合样品,您应该这样做:
否则你的计算会溢出(同样,我通常建议在操作前将音频标准化为
float
s)。还应该注意的是,你正在混合 MP3 文件中的所有字节,i.e。,你正在弄乱标题(因此 WMP 拒绝播放你的“混合”文件)。您应该只混合文件的实际音频数据(样本),而不是整个文件。我已经使用 NAudio 库提供了一个(评论过的)工作示例 1(它将混合音频导出到 wav 文件以避免进一步的复杂化):
1 输入文件必须具有相同的采样率,位深度和通道数,才能使其正常工作。