2014-05-11 74 views

回答

3

有两种方法可以剪切mp3文件。

  1. 解析mp3文件得到所有的mp3帧。复制您不想剪切的帧并将其粘贴到新的流中。
  2. 解码整个mp3文件,并重新编码你不想被剪下的数据。

第一种方法的缺点是它比方法2更复杂,并且不能精确地剪切mp3。这意味着,你被限制在MP3帧的大小。

第二种方法正是你要找的。但是有一个大问题:自Windows 8以来只支持MP3编码。这意味着您不能在Windows XP,Vista或Windows 7中使用此方法。

- >我会建议您使用任何第三方组件,如跛脚,ffmpeg的,...

反正...对方法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; 
    } 
}