forked from workgroupengineering/Spectrogram
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAudioFile.cs
More file actions
47 lines (45 loc) · 1.79 KB
/
AudioFile.cs
File metadata and controls
47 lines (45 loc) · 1.79 KB
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Spectrogram.Tests
{
public static class AudioFile
{
/// <summary>
/// Use NAudio to read the contents of a WAV file.
/// </summary>
public static (double[] audio, int sampleRate) ReadWAV(string filePath, double multiplier = 16_000)
{
using var afr = new NAudio.Wave.AudioFileReader(filePath);
int sampleRate = afr.WaveFormat.SampleRate;
int bytesPerSample = afr.WaveFormat.BitsPerSample / 8;
int sampleCount = (int)afr.Length / bytesPerSample;
int channelCount = afr.WaveFormat.Channels;
var audio = new List<double>(sampleCount);
var buffer = new float[sampleRate * channelCount];
int samplesRead = 0;
while ((samplesRead = afr.Read(buffer, 0, buffer.Length)) > 0)
audio.AddRange(buffer.Take(samplesRead).Select(x => x * multiplier));
return (audio.ToArray(), sampleRate);
}
/// <summary>
/// Use MP3Sharp to read the contents of an MP3 file.
/// </summary>
public static double[] ReadMP3(string filePath, int bufferSize = 4096)
{
List<double> audio = new List<double>();
MP3Sharp.MP3Stream stream = new MP3Sharp.MP3Stream(filePath);
byte[] buffer = new byte[bufferSize];
int bytesReturned = 1;
while (bytesReturned > 0)
{
bytesReturned = stream.Read(buffer, 0, bufferSize);
for (int i = 0; i < bytesReturned / 2 - 1; i += 2)
audio.Add(BitConverter.ToInt16(buffer, i * 2));
}
stream.Close();
return audio.ToArray();
}
}
}