【发布时间】:2014-06-28 19:02:34
【问题描述】:
是否可以使用CSCore-Library 剪切音频文件?例如,我想在第 20 秒开始播放 mp3,在第 50 秒停止播放,我想生成一个新的 mp3 文件。
【问题讨论】:
是否可以使用CSCore-Library 剪切音频文件?例如,我想在第 20 秒开始播放 mp3,在第 50 秒停止播放,我想生成一个新的 mp3 文件。
【问题讨论】:
有两种方法可以剪切 mp3 文件。
第一种方法的缺点是它比方法2更复杂,并且不能精确切割mp3。这意味着,您受限于 mp3 帧的大小。
第二种方法正是您正在寻找的。但是有一个大问题:从 Windows 8 开始才支持 MP3 编码。也就是说,你不能在 Windows XP、Vista 或 Windows 7 中使用这种方法。
--> 我建议您使用任何第三方组件,例如 lame、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;
}
}
【讨论】: