Beispiel #1
0
        private byte[]  GetBytesOfSong(string songPath)
        {
            var songFile = new AudioFileReader(songPath);

            var song   = songFile.ToMono();
            var song16 = song.ToWaveProvider16();

            var buffer = new byte[2048];
            var offset = 0;

            while (true)
            {
                var written = song16.Read(buffer, offset, buffer.Length - offset);
                if (written == 0)
                {
                    break;
                }

                offset += written;
                Array.Resize(ref buffer, buffer.Length * 2);
            }

            //trim 0s
            var firstIndex = 0;
            var lastIndex  = buffer.Length - 1;

            while (buffer[firstIndex] == 0)
            {
                firstIndex++;
            }

            while (buffer[lastIndex] == 0)
            {
                lastIndex--;
            }

            var songBytes = new byte[lastIndex - firstIndex];

            for (int write = 0, read = firstIndex; write < songBytes.Length; write++, read++)
            {
                songBytes[write] = buffer[read];
            }

            return(songBytes);
        }
        public static List <float> ReadSamples(string path, int sampleRate)
        {
            path = path ?? throw new ArgumentNullException();
            ThrowUtils.ThrowIf_FileNotExist(path);

            AudioFileReader reader = new AudioFileReader(path);

            ThrowUtils.ThrowIf_True(reader.WaveFormat.SampleRate != sampleRate,
                                    "reader.WaveFormat.SampleRate != sampleRate ({0} != {1})".Format(reader.WaveFormat.SampleRate, sampleRate));

            int totalSamples = (reader.TotalTime.TotalSeconds * sampleRate).ToInt32();

            reader.Volume = 1;
            float[] buff  = new float[totalSamples];
            var     count = reader.ToMono(1, 0).Read(buff, 0, totalSamples);

            return(buff.ToList());
        }
Beispiel #3
0
        public static (int sampleRate, float[] samples) GetSamples(
            string pathToAudioFile)
        {
            using var reader = new AudioFileReader(pathToAudioFile);

            var sampleProvider = reader.ToMono();
            var samples        =
                new float[reader.Length / sizeof(float) /
                          reader.WaveFormat.Channels];
            var samplesRead = sampleProvider.Read(samples, 0, samples.Length);

            Array.Resize(ref samples, samplesRead);

            if (samples.Length != samplesRead)
            {
                throw new Exception(
                          "Error when reading the samples, samples.Length=" +
                          samples.Length + " samplesRead=" + samplesRead);
            }

            return(reader.WaveFormat.SampleRate, samples);
        }