1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
public class NAudioHelper { private static MuLawChatCodec _codec = new MuLawChatCodec(); public static void EnCodeG711(string inFile, string outfile) { var format = new WaveFormat(8000, 16, 1); using (var reader = new WaveFileReader(inFile)) using (WaveFileWriter waveFileWriter = new WaveFileWriter(outfile, format)) { byte[] buffer = new byte[reader.WaveFormat.AverageBytesPerSecond * 4]; while (true) { int count = reader.Read(buffer, 0, buffer.Length);
byte[] encoded = _codec.Encode(buffer, 0, count);
if (count != 0) waveFileWriter.Write(encoded, 0, encoded.Length); else break; } } } public static string GetFileName() { Random rd = new Random(); StringBuilder serial = new StringBuilder(); serial.Append(DateTime.Now.ToString("yyyyMMddHHmmssff")); serial.Append(rd.Next(0, 999999).ToString()); return serial.ToString(); } }
internal class MuLawChatCodec { public string Name => "G.711 mu-law";
public int BitsPerSecond => RecordFormat.SampleRate * 8;
public WaveFormat RecordFormat => new WaveFormat(8000, 16, 1);
public byte[] Encode(byte[] data, int offset, int length) { var encoded = new byte[length / 2]; int outIndex = 0; for (int n = 0; n < length; n += 2) { encoded[outIndex++] = MuLawEncoder.LinearToMuLawSample(BitConverter.ToInt16(data, offset + n)); }
return encoded; }
public byte[] Decode(byte[] data, int offset, int length) { var decoded = new byte[length * 2]; int outIndex = 0; for (int n = 0; n < length; n++) { short decodedSample = MuLawDecoder.MuLawToLinearSample(data[n + offset]); decoded[outIndex++] = (byte)(decodedSample & 0xFF); decoded[outIndex++] = (byte)(decodedSample >> 8); }
return decoded; }
public void Dispose() { }
public bool IsAvailable { get { return true; } } }
|