mp3
using Microsoft.EntityFrameworkCore;
using NAudio.Wave;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace 一對多
{
class Program
{
static void Main(string[] args)
{
// 合併
List<string> list = new List<string>();
list.Add(@"C:\mp3\0.mp3");
list.Add(@"C:\mp3\1.mp3");
CombineFile cf = new CombineFile(list);
cf.Combine(@"C:\mp3\10.mp3");
Console.Read();
//剪輯
CombineFile com = new CombineFile();
com.CutMp3(@"C:\mp3\10.mp3", @"C:\mp3\11.mp3", 0, 448);
}
}
public class CombineFile
{
private List<string> files = new List<string>();
// 需要合并的文件
public List<string> Files
{
get
{
return files;
}
}
public CombineFile()
{
}
public CombineFile(List<string> filePath)
{
this.files = filePath;
}
public void Combine(string fullName)
{
if (!(this.files.Count > 0))
{
throw new Exception("文件列表为空");
}
foreach (string item in this.files)
{
if (!File.Exists(item))
{
throw new Exception(string.Format("文件{0}不存在", item));
}
}
byte[] buffer = new byte[1024 * 100];
using (FileStream outStream = new FileStream(fullName, FileMode.Create))
{
int readedLen = 0;
FileStream srcStream = null;
for (int i = 0; i < files.Count; i++)
{
srcStream = new FileStream(files[i], FileMode.Open);
while ((readedLen = srcStream.Read(buffer, 0, buffer.Length)) > 0)
{
outStream.Write(buffer, 0, readedLen);
}
srcStream.Close();
}
}
}
public void CutMp3(string filePath, string outputPath, int start, int end)
{
var s = TimeSpan.FromSeconds(start);
var e = TimeSpan.FromSeconds(end);
try
{
//读取mp3音频文件
using (var reader = new Mp3FileReader(filePath))
{
//创建输出剪辑文件
using (var writer = File.Create(outputPath))
{
Mp3Frame frame;
//遍历音频每一帧
while ((frame = reader.ReadNextFrame()) != null)
if (reader.CurrentTime >= s)
{
if (reader.CurrentTime <= e)
{
//时间数值属于音频时长正常范围 写入文件
writer.Write(frame.RawData, 0, frame.RawData.Length);
}
else
{
//超出音频时间范围跳出
break;
}
}
}
}
}
catch (Exception ex)
{
}
}
}
}