Esempio n. 1
0
        private static AudioKeyValues GetKeyValues(AudioFileReader reader)
        {
            var          res                  = new AudioKeyValues();
            const double volumeThreshold      = 0.009;
            const double endToleranceModifier = 0.5;
            var          startIteration       = 0;
            var          endIteration         = 0;
            var          totalIterationCount  = 0;
            var          buffer               = new float[reader.WaveFormat.SampleRate];
            int          read;

            // iterate file
            do
            {
                read = reader.Read(buffer, 0, buffer.Length);

                for (var n = 0; n < read; n++)
                {
                    totalIterationCount++;
                    var volume = Math.Abs(buffer[n]);

                    // found start trim pos
                    if (volume > volumeThreshold && startIteration == 0)
                    {
                        startIteration = totalIterationCount;
                    }

                    // update end trim pos -> less threshold/strict because a longer end is not bad
                    if (volume > volumeThreshold * endToleranceModifier)
                    {
                        endIteration = totalIterationCount;
                    }

                    // update max volume
                    if (volume > res.MaxVolume)
                    {
                        res.MaxVolume = volume;
                    }
                }
            } while (read > 0);

            // reset current position to start for future reads
            reader.Position = 0;

            if (res.MaxVolume <= 0 || res.MaxVolume > 1.0f)
            {
                throw new InvalidOperationException("File cannot be normalized");
            }

            // convert iteration# to time
            var startPercent = (double)startIteration / totalIterationCount;
            var endPercent   = (double)endIteration / totalIterationCount;

            res.StartCut = TimeSpan.FromMilliseconds(reader.TotalTime.TotalMilliseconds * startPercent);
            res.EndCut   = TimeSpan.FromMilliseconds(reader.TotalTime.TotalMilliseconds * endPercent);
            res.EndCut   = reader.TotalTime - res.EndCut;

            return(res);
        }
Esempio n. 2
0
 private static void NormalizeVolume(AudioFileReader reader, AudioKeyValues data)
 {
     reader.Volume = 1.0f / data.MaxVolume;
 }