Friday, May 30, 2025

trying to do samples handlings on wav files

 



namespace SAAN_FRESH___RAW_NON_APIS_WAVES_TO_SHRUTIES_COPIER_GPTS

{













    public class SAANS_NO_3RD_PARTY_GPT_STYLES_WAV_FILES_READER_TO_GENERATE_8000_HZ_16_BIT_PCMS_GTAMPS

    {



        //////public static void Write_SPLITTED_WavFile(string path, List<float> normalizedSamples, int sampleRate)

        //////{

        //////    short bitsPerSample = 16;

        //////    short channels = 1;

        //////    int byteRate = sampleRate * channels * bitsPerSample / 8;

        //////    int dataSize = normalizedSamples.Count * 2;


        //////    using (var writer = new BinaryWriter(File.Create(path)))

        //////    {

        //////        writer.Write(Encoding.ASCII.GetBytes("RIFF"));

        //////        writer.Write(36 + dataSize);

        //////        writer.Write(Encoding.ASCII.GetBytes("WAVE"));


        //////        writer.Write(Encoding.ASCII.GetBytes("fmt "));

        //////        writer.Write(16);

        //////        writer.Write((short)1); // PCM

        //////        writer.Write((short)channels);

        //////        writer.Write(sampleRate);

        //////        writer.Write(byteRate);

        //////        writer.Write((short)(channels * bitsPerSample / 8));

        //////        writer.Write(bitsPerSample);


        //////        writer.Write(Encoding.ASCII.GetBytes("data"));

        //////        writer.Write(dataSize);

        //////        foreach (float sample in normalizedSamples)

        //////            writer.Write((short)(sample * 32767));

        //////    }//using (var writer = new BinaryWriter(File.Create(path)))

        //////}//public static void Write_SPLITTED_WavFile(string path, List<float> normalizedSamples, int sampleRate)










































        public static void SplitWavByAmplitudePercentilewith_dynamik_thresholds(string wavPath)

        {

            string fileNameOnly = Path.GetFileNameWithoutExtension(wavPath);

            string folder = Path.GetDirectoryName(wavPath);


            short channels = 1;

            int sampleRate = 8000;

            short bitsPerSample = 16;

            List<float> amplitudes = new List<float>();


            // ---- Read WAV and extract normalized amplitudes ----

            using (var reader = new BinaryReader(File.OpenRead(wavPath)))

            {

                if (new string(reader.ReadChars(4)) != "RIFF") throw new Exception("Invalid RIFF");

                reader.ReadInt32(); // size

                if (new string(reader.ReadChars(4)) != "WAVE") throw new Exception("Invalid WAVE");


                while (reader.BaseStream.Position < reader.BaseStream.Length)

                {

                    string chunkId = new string(reader.ReadChars(4));

                    int chunkSize = reader.ReadInt32();


                    if (chunkId == "fmt ")

                    {

                        reader.ReadInt16(); // audioFormat

                        channels = reader.ReadInt16();

                        sampleRate = reader.ReadInt32();

                        reader.ReadInt32(); // byteRate

                        reader.ReadInt16(); // blockAlign

                        bitsPerSample = reader.ReadInt16();

                        if (chunkSize > 16) reader.ReadBytes(chunkSize - 16);

                    }

                    else if (chunkId == "data")

                    {

                        int bytesPerSample = bitsPerSample / 8;

                        int totalSamples = chunkSize / bytesPerSample;


                        for (int i = 0; i < totalSamples; i++)

                        {

                            if (reader.BaseStream.Position + bytesPerSample > reader.BaseStream.Length)

                                break;


                            short sample = reader.ReadInt16();

                            float norm = sample / 32768f;

                            amplitudes.Add(norm);


                            if (channels == 2) reader.ReadInt16(); // skip right channel

                        }

                        break;

                    }

                    else reader.ReadBytes(chunkSize); // skip unknown

                }

            }


            // ---- Calculate 20th percentile of absolute amplitudes ----

            var absSorted = amplitudes.Select(Math.Abs).OrderBy(v => v).ToList();

            float percentile20 = absSorted[(int)(absSorted.Count * 0.2)];


            Console.WriteLine($"Using 20th Percentile Amplitude as Threshold: {percentile20:F6}");


            // ---- Detect rising/falling threshold crossings ----

            List<(int Start, int End)> regions = new List<(int, int)>();

            bool inRegion = false;

            int regionStart = 0;

            int minSegmentSamples = 800; // ~100 ms


            for (int i = 0; i < amplitudes.Count; i++)

            {

                float absAmp = Math.Abs(amplitudes[i]);


                if (!inRegion && absAmp >= percentile20)

                {

                    inRegion = true;

                    regionStart = i;

                }

                else if (inRegion && absAmp < percentile20)

                {

                    int regionEnd = i;

                    if (regionEnd - regionStart >= minSegmentSamples)

                        regions.Add((regionStart, regionEnd));

                    inRegion = false;

                }

            }


            // Handle edge case if region reaches file end

            if (inRegion && amplitudes.Count - regionStart >= minSegmentSamples)

                regions.Add((regionStart, amplitudes.Count - 1));


            // ---- Save split WAVs ----

            for (int i = 0; i < regions.Count; i++)

            {

                int start = regions[i].Start;

                int end = regions[i].End;

                var segment = amplitudes.GetRange(start, end - start);


                string outputFile = Path.Combine(folder,

                    $"{fileNameOnly}_piece_{i + 1}_samples_{segment.Count}_ms_{(int)(segment.Count / (float)sampleRate * 1000)}.wav");


                Write_SPLITTED_WavFile(outputFile, segment, sampleRate);

                Console.WriteLine($"Saved: {outputFile}");

            }


            if (regions.Count == 0)

                Console.WriteLine("No regions above the 20th percentile threshold were long enough to save.");

        }//public static void SplitWavByAmplitudePercentilewith_dynamik_thresholds(string wavPath)






        public static void SplitWavByRisingAbove20dBRegions(string wavPath)

        {

            string fileNameOnly = Path.GetFileNameWithoutExtension(wavPath);

            string folder = Path.GetDirectoryName(wavPath);


            short channels = 1;

            int sampleRate = 8000;

            short bitsPerSample = 16;

            List<float> amplitudes = new List<float>();


            // ---- Read WAV and extract normalized amplitudes ----

            using (var reader = new BinaryReader(File.OpenRead(wavPath)))

            {

                // Read RIFF/WAVE

                if (new string(reader.ReadChars(4)) != "RIFF") throw new Exception("Invalid RIFF");

                reader.ReadInt32(); // size

                if (new string(reader.ReadChars(4)) != "WAVE") throw new Exception("Invalid WAVE");


                while (reader.BaseStream.Position < reader.BaseStream.Length)

                {

                    string chunkId = new string(reader.ReadChars(4));

                    int chunkSize = reader.ReadInt32();


                    if (chunkId == "fmt ")

                    {

                        reader.ReadInt16(); // audioFormat

                        channels = reader.ReadInt16();

                        sampleRate = reader.ReadInt32();

                        reader.ReadInt32(); // byteRate

                        reader.ReadInt16(); // blockAlign

                        bitsPerSample = reader.ReadInt16();

                        if (chunkSize > 16) reader.ReadBytes(chunkSize - 16);

                    }

                    else if (chunkId == "data")

                    {

                        int bytesPerSample = bitsPerSample / 8;

                        int totalSamples = chunkSize / bytesPerSample;


                        for (int i = 0; i < totalSamples; i++)

                        {

                            if (reader.BaseStream.Position + bytesPerSample > reader.BaseStream.Length)

                                break;


                            short sample = reader.ReadInt16();

                            float norm = sample / 32768f;

                            amplitudes.Add(norm);


                            if (channels == 2) reader.ReadInt16(); // skip right

                        }

                        break;

                    }

                    else reader.ReadBytes(chunkSize);

                }

            }


            // ---- SPLITTING BASED ON AMPLITUDE THRESHOLD ----

            float threshold = 0.1f; // ~ -20 dB

            bool inRegion = false;

            int regionStart = 0;

            int minSegmentSamples = 800; // = 100ms worth (8000Hz)


            List<(int Start, int End)> regions = new List<(int, int)>();


            for (int i = 0; i < amplitudes.Count; i++)

            {

                float absAmp = Math.Abs(amplitudes[i]);


                if (!inRegion && absAmp >= threshold)

                {

                    inRegion = true;

                    regionStart = i;

                }

                else if (inRegion && absAmp < threshold)

                {

                    // End of region

                    int regionEnd = i;

                    if (regionEnd - regionStart >= minSegmentSamples)

                        regions.Add((regionStart, regionEnd));

                    inRegion = false;

                }

            }//for (int i = 0; i < amplitudes.Count; i++)


            // Edge case: still in region at end

            if (inRegion && amplitudes.Count - regionStart >= minSegmentSamples)

                regions.Add((regionStart, amplitudes.Count - 1));


            // ---- SAVE SPLIT WAVS ----

            for (int i = 0; i < regions.Count; i++)

            {

                int start = regions[i].Start;

                int end = regions[i].End;

                var segment = amplitudes.GetRange(start, end - start);


                string outputFile = Path.Combine(folder,

                    $"{fileNameOnly}_piece_{i + 1}_samples_{segment.Count}_ms_{(int)(segment.Count / (float)sampleRate * 1000)}.wav");


                Write_SPLITTED_WavFile(outputFile, segment, sampleRate);

                Console.WriteLine($"Saved: {outputFile}");

            }//for (int i = 0; i < regions.Count; i++)

        }//public static void SplitWavByRisingAbove20dBRegions(string wavPath)



        public static void DISCARDING___THIS_GENERATES_LARGE_NUMBER_OF_SPLITTED_FILES______SplitWavByLocalMinimals_Of_Amplitudes(string wavPath)

        {

            string fileNameOnly = Path.GetFileNameWithoutExtension(wavPath);

            string folder = Path.GetDirectoryName(wavPath);


            short channels = 1;

            int sampleRate = 8000;

            short bitsPerSample = 16;

            List<float> amplitudes = new List<float>();


            // ---- Read WAV and extract normalized amplitudes ----

            using (var reader = new BinaryReader(File.OpenRead(wavPath)))

            {

                // Validate RIFF and WAVE

                if (new string(reader.ReadChars(4)) != "RIFF") throw new Exception("Invalid RIFF");

                reader.ReadInt32(); // size

                if (new string(reader.ReadChars(4)) != "WAVE") throw new Exception("Invalid WAVE");


                while (reader.BaseStream.Position < reader.BaseStream.Length)

                {

                    string chunkId = new string(reader.ReadChars(4));

                    int chunkSize = reader.ReadInt32();


                    if (chunkId == "fmt ")

                    {

                        reader.ReadInt16(); // audioFormat

                        channels = reader.ReadInt16();

                        sampleRate = reader.ReadInt32();

                        reader.ReadInt32(); // byteRate

                        reader.ReadInt16(); // blockAlign

                        bitsPerSample = reader.ReadInt16();

                        if (chunkSize > 16) reader.ReadBytes(chunkSize - 16);

                    }

                    else if (chunkId == "data")

                    {

                        int bytesPerSample = bitsPerSample / 8;

                        int totalSamples = chunkSize / bytesPerSample;


                        for (int i = 0; i < totalSamples; i++)

                        {

                            if (reader.BaseStream.Position + bytesPerSample > reader.BaseStream.Length)

                                break;


                            short sample = reader.ReadInt16();

                            float norm = sample / 32768f;

                            amplitudes.Add(norm);


                            if (channels == 2) reader.ReadInt16(); // skip right

                        }

                        break;

                    }

                    else reader.ReadBytes(chunkSize); // skip unknown chunk

                }

            }


            // ---- Analyze: average and percentiles ----

            float avgAmp = amplitudes.Average(a => Math.Abs(a));

            float percentile20 = amplitudes.OrderBy(Math.Abs).ElementAt((int)(amplitudes.Count * 0.2f));

            float percentile50 = amplitudes.OrderBy(Math.Abs).ElementAt((int)(amplitudes.Count * 0.5f));


            Console.WriteLine($"Average Amplitude: {avgAmp:F4}");

            Console.WriteLine($"20th Percentile: {percentile20:F4}, 50th Percentile: {percentile50:F4}");


            // ---- Detect local minima ----

            List<int> minimaIndexes = new List<int>();

            for (int i = 1; i < amplitudes.Count - 1; i++)

            {

                if (Math.Abs(amplitudes[i]) < Math.Abs(amplitudes[i - 1]) &&

                    Math.Abs(amplitudes[i]) < Math.Abs(amplitudes[i + 1]))

                {

                    if (Math.Abs(amplitudes[i]) < percentile20)

                        minimaIndexes.Add(i);

                }

            }//for (int i = 1; i < amplitudes.Count - 1; i++)


            // ---- Extract segments between minima and save WAVs ----

            for (int i = 0; i < minimaIndexes.Count - 1; i++)

            {

                int start = minimaIndexes[i];

                int end = minimaIndexes[i + 1];

                var segment = amplitudes.GetRange(start, end - start);


                string outputFile = Path.Combine(folder,

                    $"{fileNameOnly}_piece_{i + 1}_samples_{segment.Count}_ms_{(int)(segment.Count / (float)sampleRate * 1000)}.wav");


                Write_SPLITTED_WavFile(outputFile, segment, sampleRate);

                Console.WriteLine($"Saved: {outputFile}");

            }//for (int i = 0; i < minimaIndexes.Count - 1; i++)










        }//public static void DISCARDING___THIS_GENERATES_LARGE_NUMBER_OF_SPLITTED_FILES______SplitWavByLocalMinimals_Of_Amplitudes(string wavPath)




        public static void Write_SPLITTED_WavFile(string path, List<float> normalizedSamples, int sampleRate)

        {

            short bitsPerSample = 16;

            short channels = 1;

            int byteRate = sampleRate * channels * bitsPerSample / 8;

            int dataSize = normalizedSamples.Count * 2;


            using (var writer = new BinaryWriter(File.Create(path)))

            {

                // RIFF header

                writer.Write(Encoding.ASCII.GetBytes("RIFF"));

                writer.Write(36 + dataSize);

                writer.Write(Encoding.ASCII.GetBytes("WAVE"));


                // fmt chunk

                writer.Write(Encoding.ASCII.GetBytes("fmt "));

                writer.Write(16);

                writer.Write((short)1); // PCM

                writer.Write((short)channels);

                writer.Write(sampleRate);

                writer.Write(byteRate);

                writer.Write((short)(channels * bitsPerSample / 8));

                writer.Write(bitsPerSample);


                // data chunk

                writer.Write(Encoding.ASCII.GetBytes("data"));

                writer.Write(dataSize);

                foreach (float sample in normalizedSamples)

                    writer.Write((short)(sample * 32767));

            }

        }//public static void Write_SPLITTED_WavFile(string path, List<float> normalizedSamples, int sampleRate)



        public static double PrintWavDurationAndSampleCount(string wavPath)

        {

            double durationMs = 0;

            string ___report = "";


            using (var reader = new BinaryReader(File.OpenRead(wavPath)))

            {

                // Skip RIFF header

                reader.ReadChars(4);

                reader.ReadInt32();

                reader.ReadChars(4);


                int sampleRate = 0;

                short channels = 1;

                short bitsPerSample = 16;

                int dataSize = 0;


                // Read chunks

                while (reader.BaseStream.Position < reader.BaseStream.Length)

                {

                    string chunkId = new string(reader.ReadChars(4));

                    int chunkSize = reader.ReadInt32();


                    if (chunkId == "fmt ")

                    {

                        short audioFormat = reader.ReadInt16();

                        channels = reader.ReadInt16();

                        sampleRate = reader.ReadInt32();

                        reader.ReadInt32(); // byteRate

                        reader.ReadInt16(); // blockAlign

                        bitsPerSample = reader.ReadInt16();


                        if (chunkSize > 16)

                            reader.ReadBytes(chunkSize - 16);

                    }

                    else if (chunkId == "data")

                    {

                        dataSize = chunkSize;

                        break;

                    }

                    else

                    {

                        reader.ReadBytes(chunkSize); // skip unknown chunk

                    }

                }//while (reader.BaseStream.Position < reader.BaseStream.Length)


                if (sampleRate == 0 || dataSize == 0)

                {

                    Console.WriteLine("Failed to read sample rate or data size.");

                    return 0;

                }//if (sampleRate == 0 || dataSize == 0)



































                int bytesPerSample = bitsPerSample / 8 * channels;

                int totalSamples = dataSize / bytesPerSample;

                 durationMs = (totalSamples / (double)sampleRate) * 1000;


                Console.WriteLine($"Sample Rate      : {sampleRate} Hz");

                Console.WriteLine($"Channels         : {channels}");

                Console.WriteLine($"Bits Per Sample  : {bitsPerSample}");

                Console.WriteLine($"Total Samples    : {totalSamples}");

                Console.WriteLine($"Total Duration   : {durationMs:F2} ms");


                












                 ___report= ___report + "\r\n"+ ($"Sample Rate      : {sampleRate} Hz");

                ___report = ___report + "\r\n" + ($"Channels         : {channels}");

                ___report = ___report + "\r\n" + ($"Bits Per Sample  : {bitsPerSample}");

                ___report = ___report + "\r\n" + ($"Total Samples    : {totalSamples}");

                ___report = ___report + "\r\n" + ($"Total Duration   : {durationMs:F2} ms");



                System.IO.File.WriteAllText(wavPath + "_reportfor_gtsmps.txt", ___report);

            }//using (var reader = new BinaryReader(File.OpenRead(wavPath)))

            return durationMs;

        }//public static void PrintWavDurationAndSampleCount(string wavPath)



        public static void ConvertWavToGTAMPS___with_corrections_GPT(string wavPath, string outputGtampsPath)

        {


            short channels = 1;

            int sampleRate = 8000;

            short bitsPerSample = 16;

            using (var reader = new BinaryReader(File.OpenRead(wavPath)))

            {

                // 1. Read RIFF header

                if (new string(reader.ReadChars(4)) != "RIFF")

                    throw new Exception("Not a valid RIFF file.");

                reader.ReadInt32(); // File size

                if (new string(reader.ReadChars(4)) != "WAVE")

                    throw new Exception("Not a valid WAVE file.");


                // 2. Find 'fmt ' subchunk

                 channels = 1;

                 sampleRate = 8000;

                 bitsPerSample = 16;

                while (true)

                {

                    string chunkId = new string(reader.ReadChars(4));

                    int chunkSize = reader.ReadInt32();


                    if (chunkId == "fmt ")

                    {

                        short audioFormat = reader.ReadInt16();

                        channels = reader.ReadInt16();

                        sampleRate = reader.ReadInt32();

                        reader.ReadInt32(); // byteRate

                        reader.ReadInt16(); // blockAlign

                        bitsPerSample = reader.ReadInt16();


                        if (chunkSize > 16)

                            reader.ReadBytes(chunkSize - 16); // skip extra fmt bytes

                        break;

                    }

                    else

                    {

                        reader.ReadBytes(chunkSize); // skip unknown chunk

                    }

                }


                // 3. Find 'data' subchunk

                while (true)

                {

                    string chunkId = new string(reader.ReadChars(4));

                    int chunkSize = reader.ReadInt32();

                    if (chunkId == "data")

                    {

                        int bytesPerSample = bitsPerSample / 8;

                        int totalSamples = chunkSize / bytesPerSample;

                        var amplitudes = new List<float>();


                        for (int i = 0; i < totalSamples; i++)

                        {

                            if (reader.BaseStream.Position + bytesPerSample > reader.BaseStream.Length)

                                break;


                            short sample = reader.ReadInt16();

                            float norm = sample / 32768f;

                            amplitudes.Add(norm);


                            if (channels == 2)

                                reader.ReadInt16(); // skip right channel

                        }


                        // 4. Resample if needed

                        if (sampleRate != 8000)

                        {

                            var resampled = new List<float>();

                            double factor = sampleRate / 8000.0;

                            for (int i = 0; i < amplitudes.Count / factor; i++)

                            {

                                double idx = i * factor;

                                int i0 = (int)idx;

                                double frac = idx - i0;

                                float val = (i0 + 1 < amplitudes.Count)

                                    ? (float)((1 - frac) * amplitudes[i0] + frac * amplitudes[i0 + 1])

                                    : amplitudes[i0];

                                resampled.Add(val);

                            }

                            amplitudes = resampled;

                        }
















                        // 5. Save GTAMPS

                          File.WriteAllLines(outputGtampsPath, amplitudes.Select(a => a.ToString("F8")));

                           Console.WriteLine($"Saved GTAMPS: {outputGtampsPath}");


                        System.Windows.Forms.MessageBox.Show($"Saved GTAMPS: {outputGtampsPath}   amplitudes =  {amplitudes.Count}");














                       //     string outputGtampsPath_generated = wavPath + "_actual_sampleRate=" + sampleRate + "_actual_bps=" + bitsPerSample + "_numSamples=" + numSamples + "_smpls=" + samples + "_8000Hz_16_bits_pcms_" + ".GTAMPS";

                       //samples

                       // Save as .GTAMPS

                       //   File.WriteAllLines(outputGtampsPath_generated, samples.Select(s => s.ToString("F8")));



                        return;

                    }

                    else

                    {

                        reader.ReadBytes(chunkSize); // skip unknown chunk

                    }

                }


                throw new Exception("Data chunk not found.");

            }

        }//public static void ConvertWavToGTAMPS___with_corrections_GPT(string wavPath, string outputGtampsPath)



        //////    public static void ConvertWavToGTAMPS___with_corrections_GPT(string wavPath, string outputGtampsPath)

        //////    {

        //////        using (var reader = new BinaryReader(File.OpenRead(wavPath)))

        //////        {

        //////            // 1. Read RIFF header

        //////            if (new string(reader.ReadChars(4)) != "RIFF")

        //////                throw new Exception("Not a valid RIFF file.");

        //////            reader.ReadInt32(); // File size

        //////            if (new string(reader.ReadChars(4)) != "WAVE")

        //////                throw new Exception("Not a valid WAVE file.");


        //////            // 2. Find 'fmt ' subchunk

        //////            short channels = 1;

        //////            int sampleRate = 8000;

        //////            short bitsPerSample = 16;

        //////            while (true)

        //////            {

        //////                string chunkId = new string(reader.ReadChars(4));

        //////                int chunkSize = reader.ReadInt32();


        //////                if (chunkId == "fmt ")

        //////                {

        //////                    short audioFormat = reader.ReadInt16();

        //////                    channels = reader.ReadInt16();

        //////                    sampleRate = reader.ReadInt32();

        //////                    reader.ReadInt32(); // byteRate

        //////                    reader.ReadInt16(); // blockAlign

        //////                    bitsPerSample = reader.ReadInt16();


        //////                    if (chunkSize > 16)

        //////                        reader.ReadBytes(chunkSize - 16); // skip extra fmt bytes

        //////                    break;

        //////                }

        //////                else

        //////                {

        //////                    reader.ReadBytes(chunkSize); // skip unknown chunk

        //////                }

        //////            }


        //////            // 3. Find 'data' subchunk

        //////            while (true)

        //////            {

        //////                string chunkId = new string(reader.ReadChars(4));

        //////                int chunkSize = reader.ReadInt32();

        //////                if (chunkId == "data")

        //////                {

        //////                    int bytesPerSample = bitsPerSample / 8;

        //////                    int totalSamples = chunkSize / bytesPerSample;

        //////                    var amplitudes = new List<float>();


        //////                    for (int i = 0; i < totalSamples; i++)

        //////                    {

        //////                        if (reader.BaseStream.Position + bytesPerSample > reader.BaseStream.Length)

        //////                        { break; }


        //////                        short sample = reader.ReadInt16();

        //////                        float norm = sample / 32768f;

        //////                        amplitudes.Add(norm);


        //////                        if (channels == 2)

        //////                        {

        //////                            reader.ReadInt16(); // skip right channel}

        //////                        }// for (int i = 0; i < totalSamples; i++)


        //////                        // 4. Resample if needed

        //////                        if (sampleRate != 8000)

        //////                    {

        //////                        var resampled = new List<float>();

        //////                        double factor = sampleRate / 8000.0;

        //////                        for (int rrr = 0; rrr < amplitudes.Count / factor; rrr++)

        //////                        {

        //////                            double idx = rrr * factor;

        //////                            int i0 = (int)idx;

        //////                            double frac = idx - i0;

        //////                            float val = (i0 + 1 < amplitudes.Count)

        //////                                ? (float)((1 - frac) * amplitudes[i0] + frac * amplitudes[i0 + 1])

        //////                                : amplitudes[i0];

        //////                            resampled.Add(val);

        //////                        }//for (int rrr = 0; rrr < amplitudes.Count / factor; rrr++)

        //////                        amplitudes = resampled;

        //////                    }//if (sampleRate != 8000)


        //////                    // 5. Save GTAMPS

        //////                    //   File.WriteAllLines(outputGtampsPath, amplitudes.Select(a => a.ToString("F8")));

        //////                    //   Console.WriteLine($"Saved GTAMPS: {outputGtampsPath}");
















        //////                    string outputGtampsPath_generated = wavPath + "_actual_sampleRate=" + sampleRate + "_actual_bps=" + bitsPerSample + "_numSamples=" + numSamples + "_smpls=" + samples + "_8000Hz_16_bits_pcms_" + ".GTAMPS";

        //////                    //samples

        //////                    // Save as .GTAMPS

        //////                    File.WriteAllLines(outputGtampsPath_generated, samples.Select(s => s.ToString("F8")));



        //////                    return;

        //////                }

        //////                else

        //////                {

        //////                    reader.ReadBytes(chunkSize); // skip unknown chunk

        //////                }

        //////            }


        //////            throw new Exception("Data chunk not found.");

        //////        }

        //////    }//public static void ConvertWavToGTAMPS___with_corrections_GPT(string wavPath, string outputGtampsPath)



        //////    public static void ConvertANY_KIND_OF_WavToGTAMPS(string wavPath, string outputGtampsPath)

        //////    {

        //////        using (var reader = new BinaryReader(File.OpenRead(wavPath)))

        //////        {

        //////            // Read RIFF header

        //////            string riff = new string(reader.ReadChars(4));

        //////            int fileSize = reader.ReadInt32();

        //////            string wave = new string(reader.ReadChars(4));


        //////            // Read format chunk

        //////            string fmt = new string(reader.ReadChars(4));

        //////            int fmtSize = reader.ReadInt32();

        //////            short audioFormat = reader.ReadInt16();

        //////            short channels = reader.ReadInt16();

        //////            int sampleRate = reader.ReadInt32();

        //////            int byteRate = reader.ReadInt32();

        //////            short blockAlign = reader.ReadInt16();

        //////            short bitsPerSample = reader.ReadInt16();


        //////            // Skip any extra bytes if fmt chunk > 16

        //////            if (fmtSize > 16)

        //////            { reader.ReadBytes(fmtSize - 16); }


        //////            // Seek to data chunk

        //////            while (new string(reader.ReadChars(4)) != "data")

        //////            {

        //////                reader.BaseStream.Position -= 3;

        //////            }//while (new string(reader.ReadChars(4)) != "data")








        //////            int dataSize = reader.ReadInt32();


        //////            int numSamples = dataSize / (bitsPerSample / 8);

        //////            var samples = new List<float>(numSamples);


        //////            for (int i = 0; i < numSamples; i++)

        //////            {

        //////                short sample16 = reader.ReadInt16();

        //////                float normalized = sample16 / 32768f;

        //////                samples.Add(normalized);

        //////                if (channels == 2) reader.ReadInt16(); // Skip second channel if stereo

        //////            }//for (int i = 0; i < numSamples; i++)


        //////            // Resample if needed (e.g., from 44100Hz to 8000Hz)

        //////            if (sampleRate != 8000)

        //////            {

        //////                var resampled = new List<float>();

        //////                double factor = sampleRate / 8000.0;



        //////                for (int i = 0; i < samples.Count / factor; i++)

        //////                {

        //////                    double index = i * factor;

        //////                    int idx = (int)index;

        //////                    double frac = index - idx;

        //////                    float sample = (idx + 1 < samples.Count)

        //////                        ? (float)((1 - frac) * samples[idx] + frac * samples[idx + 1])

        //////                        : samples[idx];

        //////                    resampled.Add(sample);

        //////                }//for (int i = 0; i < samples.Count / factor; i++)

        //////                samples = resampled;

        //////            }//if (sampleRate != 8000)


        //////           string  outputGtampsPath_generated= wavPath+ "_actual_sampleRate=" + sampleRate + "_actual_bps="+ bitsPerSample + "_numSamples=" + numSamples + "_smpls="+ samples+ "_8000Hz_16_bits_pcms_" + ".GTAMPS";

        //////            //samples

        //////            // Save as .GTAMPS

        //////            File.WriteAllLines(outputGtampsPath_generated, samples.Select(s => s.ToString("F8")));

        //////            // Console.WriteLine($"Saved GTAMPS to: {outputGtampsPath}");


        //////            System.Windows.Forms.MessageBox.Show($"Saved GTAMPS to: {outputGtampsPath}");

        //////        }//using (var reader = new BinaryReader(File.OpenRead(wavPath)))














        //////    }//public static void ConvertWavToGTAMPS(string wavPath, string outputGtampsPath)


    }// public class SAANS_NO_3RD_PARTY_GPT_STYLES_WAV_FILES_READER_TO_GENERATE_8000_HZ_16_BIT_PCMS_GTAMPS


    public class WavGenerator___44_SHRUTIS_BACKWARD_TO_FORWARDS_Reads_GTAMPS_MONO_8000_Hz_Samples_16_bits_no_3rd_party_apis

    {

        const int SampleRate = 8000;

        const int BitsPerSample = 16;

        const int Channels = 1;

        const double Pi = Math.PI;



 


        public static void SAANS___44_SAMPLES_WavGenerator___Reads_GTAMPS_MONO_8000_Hz_Samples_16_bits_no_3rd_party_apis___Main(string gtamps_filesnames)

        {

            string inputPath = gtamps_filesnames;// "your_file_path_here.txt";



            // Read float samples

            var samples = File.ReadLines(inputPath)

                              .Where(line => double.TryParse(line, out _))

                              .Select(double.Parse)

                              .ToList();


            var allShifted = new List<short>();


            for (int r = 1; r <= 22; r++)

            {

                double shiftFactor = Math.Pow(2, r / 22.0);

                var shifted = ResampleWithFrequencyShift(samples, shiftFactor);

                allShifted.AddRange(shifted);

            }//for (int r = 1; r <= 22; r++)




            for (int r = -22; r <= 0; r++)

            {

                double shiftFactor = Math.Pow(2, r / 22.0);

                var shifted = ResampleWithFrequencyShift(samples, shiftFactor);

                allShifted.AddRange(shifted);

            }//for (int r = -22; r <= 0; r++)





            string outputPath = inputPath + "___44_SCALES_8000hZ_16_BITS_PCMS_" + allShifted.Count.ToString() + "_output.wav";


            WriteWavFile(outputPath, allShifted);

            Console.WriteLine("WAV file written to: " + outputPath);

        }//public static void SAANS___44_SAMPLES_WavGenerator___Reads_GTAMPS_MONO_8000_Hz_Samples_16_bits_no_3rd_party_apis___Main(STRING gtamps_filesnames)


        public static List<short> ResampleWithFrequencyShift(List<double> samples, double shiftFactor)

        {

            int newLength = (int)(samples.Count / shiftFactor);

            var shifted = new List<short>(newLength);


            for (int i = 0; i < newLength; i++)

            {

                double srcIndex = i * shiftFactor;

                int idx = (int)srcIndex;

                double frac = srcIndex - idx;


                double value = 0;

                if (idx + 1 < samples.Count)

                    value = (1 - frac) * samples[idx] + frac * samples[idx + 1];

                else if (idx < samples.Count)

                    value = samples[idx];


                short pcmVal = (short)(value * short.MaxValue);

                shifted.Add(pcmVal);

            }//for (int i = 0; i < newLength; i++)


            return shifted;

        }//public static List<short> ResampleWithFrequencyShift(List<double> samples, double shiftFactor)


        public static void WriteWavFile(string filePath, List<short> samples)

        {

            using (var stream = new FileStream(filePath, FileMode.Create))

            using (var writer = new BinaryWriter(stream))

            {

                int byteRate = SampleRate * Channels * BitsPerSample / 8;

                int dataSize = samples.Count * BitsPerSample / 8;


                // RIFF header

                writer.Write(Encoding.ASCII.GetBytes("RIFF"));

                writer.Write(36 + dataSize);

                writer.Write(Encoding.ASCII.GetBytes("WAVE"));


                // fmt subchunk

                writer.Write(Encoding.ASCII.GetBytes("fmt "));

                writer.Write(16); // PCM

                writer.Write((short)1); // AudioFormat = PCM

                writer.Write((short)Channels);

                writer.Write(SampleRate);

                writer.Write(byteRate);

                writer.Write((short)(Channels * BitsPerSample / 8));

                writer.Write((short)BitsPerSample);


                // data subchunk

                writer.Write(Encoding.ASCII.GetBytes("data"));

                writer.Write(dataSize);

                foreach (short s in samples)

                { writer.Write(s); }

            }//using (var writer = new BinaryWriter(stream))

        }//public static void WriteWavFile(string filePath, List<short> samples)

    }// public class WavGenerator___44_SHRUTIS_BACKWARD_TO_FORWARDS_Reads_GTAMPS_MONO_8000_Hz_Samples_16_bits_no_3rd_party_apis




    




    /// <summary>

    /// /////////////////////////////////////////////////////////////////////////////////////

    /// </summary>



    public class WavGenerator___Reads_GTAMPS_MONO_8000_Hz_Samples_16_bits_no_3rd_party_apis

    {

        const int SampleRate = 8000;

        const int BitsPerSample = 16;

        const int Channels = 1;

        const double Pi = Math.PI;


        public static void SAANS___WavGenerator___Reads_GTAMPS_MONO_8000_Hz_Samples_16_bits_no_3rd_party_apis___Main(string gtamps_filesnames)

        {

            string inputPath = gtamps_filesnames;// "your_file_path_here.txt";

           


            // Read float samples

            var samples = File.ReadLines(inputPath)

                              .Where(line => double.TryParse(line, out _))

                              .Select(double.Parse)

                              .ToList();


            var allShifted = new List<short>();


            for (int r = 1; r <= 22; r++)

            {

                double shiftFactor = Math.Pow(2, r / 22.0);

                var shifted = ResampleWithFrequencyShift(samples, shiftFactor);

                allShifted.AddRange(shifted);

            }//for (int r = 1; r <= 22; r++)



            string outputPath = inputPath + "___22_times_8000hZ_16_BITS_PCMS_"+allShifted.Count.ToString() + "_output.wav";


            WriteWavFile(outputPath, allShifted);

            Console.WriteLine("WAV file written to: " + outputPath);

        }//public static void SAANS___WavGenerator___Reads_GTAMPS_MONO_8000_Hz_Samples_16_bits_no_3rd_party_apis___Main(STRING gtamps_filesnames)


        public static List<short> ResampleWithFrequencyShift(List<double> samples, double shiftFactor)

        {

            int newLength = (int)(samples.Count / shiftFactor);

            var shifted = new List<short>(newLength);


            for (int i = 0; i < newLength; i++)

            {

                double srcIndex = i * shiftFactor;

                int idx = (int)srcIndex;

                double frac = srcIndex - idx;


                double value = 0;

                if (idx + 1 < samples.Count)

                    value = (1 - frac) * samples[idx] + frac * samples[idx + 1];

                else if (idx < samples.Count)

                    value = samples[idx];


                short pcmVal = (short)(value * short.MaxValue);

                shifted.Add(pcmVal);

            }//for (int i = 0; i < newLength; i++)


            return shifted;

        }//public static List<short> ResampleWithFrequencyShift(List<double> samples, double shiftFactor)


        public static void WriteWavFile(string filePath, List<short> samples)

        {

            using (var stream = new FileStream(filePath, FileMode.Create))

            using (var writer = new BinaryWriter(stream))

            {

                int byteRate = SampleRate * Channels * BitsPerSample / 8;

                int dataSize = samples.Count * BitsPerSample / 8;


                // RIFF header

                writer.Write(Encoding.ASCII.GetBytes("RIFF"));

                writer.Write(36 + dataSize);

                writer.Write(Encoding.ASCII.GetBytes("WAVE"));


                // fmt subchunk

                writer.Write(Encoding.ASCII.GetBytes("fmt "));

                writer.Write(16); // PCM

                writer.Write((short)1); // AudioFormat = PCM

                writer.Write((short)Channels);

                writer.Write(SampleRate);

                writer.Write(byteRate);

                writer.Write((short)(Channels * BitsPerSample / 8));

                writer.Write((short)BitsPerSample);


                // data subchunk

                writer.Write(Encoding.ASCII.GetBytes("data"));

                writer.Write(dataSize);

                foreach (short s in samples)

                { writer.Write(s); }

            }//using (var writer = new BinaryWriter(stream))

        }//public static void WriteWavFile(string filePath, List<short> samples)

    }//public class WavGenerator___Reads_GTAMPS_MONO_8000_Hz_Samples_16_bits_no_3rd_party_apis







}//namespace SAAN_FRESH___RAW_NON_APIS_WAVES_TO_SHRUTIES_COPIER_GPTS



TO DO WE GENERATED 22 LOW SHRUTIS AND 22 HIGH SHRUTIS FOR SAME RAGAS with 44 times shrutis completes.mp4

R___DES


\


WE GENERATED 22 LOW SHRUTIS AND 22 HIGH SHRUTIS FOR SAME RAGAS with 44 times shrutis completes.mp4

important codes for reading the wavs and writing 44 shrutis and gtamps NO APIS

 


namespace SAAN_FRESH___RAW_NON_APIS_WAVES_TO_SHRUTIES_COPIER_GPTS

{













    public class SAANS_NO_3RD_PARTY_GPT_STYLES_WAV_FILES_READER_TO_GENERATE_8000_HZ_16_BIT_PCMS_GTAMPS

    {







        public static double PrintWavDurationAndSampleCount(string wavPath)

        {

            double durationMs = 0;

            string ___report = "";


            using (var reader = new BinaryReader(File.OpenRead(wavPath)))

            {

                // Skip RIFF header

                reader.ReadChars(4);

                reader.ReadInt32();

                reader.ReadChars(4);


                int sampleRate = 0;

                short channels = 1;

                short bitsPerSample = 16;

                int dataSize = 0;


                // Read chunks

                while (reader.BaseStream.Position < reader.BaseStream.Length)

                {

                    string chunkId = new string(reader.ReadChars(4));

                    int chunkSize = reader.ReadInt32();


                    if (chunkId == "fmt ")

                    {

                        short audioFormat = reader.ReadInt16();

                        channels = reader.ReadInt16();

                        sampleRate = reader.ReadInt32();

                        reader.ReadInt32(); // byteRate

                        reader.ReadInt16(); // blockAlign

                        bitsPerSample = reader.ReadInt16();


                        if (chunkSize > 16)

                            reader.ReadBytes(chunkSize - 16);

                    }

                    else if (chunkId == "data")

                    {

                        dataSize = chunkSize;

                        break;

                    }

                    else

                    {

                        reader.ReadBytes(chunkSize); // skip unknown chunk

                    }

                }//while (reader.BaseStream.Position < reader.BaseStream.Length)


                if (sampleRate == 0 || dataSize == 0)

                {

                    Console.WriteLine("Failed to read sample rate or data size.");

                    return 0;

                }//if (sampleRate == 0 || dataSize == 0)



































                int bytesPerSample = bitsPerSample / 8 * channels;

                int totalSamples = dataSize / bytesPerSample;

                 durationMs = (totalSamples / (double)sampleRate) * 1000;


                Console.WriteLine($"Sample Rate      : {sampleRate} Hz");

                Console.WriteLine($"Channels         : {channels}");

                Console.WriteLine($"Bits Per Sample  : {bitsPerSample}");

                Console.WriteLine($"Total Samples    : {totalSamples}");

                Console.WriteLine($"Total Duration   : {durationMs:F2} ms");


                












                 ___report= ___report + "\r\n"+ ($"Sample Rate      : {sampleRate} Hz");

                ___report = ___report + "\r\n" + ($"Channels         : {channels}");

                ___report = ___report + "\r\n" + ($"Bits Per Sample  : {bitsPerSample}");

                ___report = ___report + "\r\n" + ($"Total Samples    : {totalSamples}");

                ___report = ___report + "\r\n" + ($"Total Duration   : {durationMs:F2} ms");



                System.IO.File.WriteAllText(wavPath + "_reportfor_gtsmps.txt", ___report);

            }//using (var reader = new BinaryReader(File.OpenRead(wavPath)))

            return durationMs;

        }//public static void PrintWavDurationAndSampleCount(string wavPath)



        public static void ConvertWavToGTAMPS___with_corrections_GPT(string wavPath, string outputGtampsPath)

        {


            short channels = 1;

            int sampleRate = 8000;

            short bitsPerSample = 16;

            using (var reader = new BinaryReader(File.OpenRead(wavPath)))

            {

                // 1. Read RIFF header

                if (new string(reader.ReadChars(4)) != "RIFF")

                    throw new Exception("Not a valid RIFF file.");

                reader.ReadInt32(); // File size

                if (new string(reader.ReadChars(4)) != "WAVE")

                    throw new Exception("Not a valid WAVE file.");


                // 2. Find 'fmt ' subchunk

                 channels = 1;

                 sampleRate = 8000;

                 bitsPerSample = 16;

                while (true)

                {

                    string chunkId = new string(reader.ReadChars(4));

                    int chunkSize = reader.ReadInt32();


                    if (chunkId == "fmt ")

                    {

                        short audioFormat = reader.ReadInt16();

                        channels = reader.ReadInt16();

                        sampleRate = reader.ReadInt32();

                        reader.ReadInt32(); // byteRate

                        reader.ReadInt16(); // blockAlign

                        bitsPerSample = reader.ReadInt16();


                        if (chunkSize > 16)

                            reader.ReadBytes(chunkSize - 16); // skip extra fmt bytes

                        break;

                    }

                    else

                    {

                        reader.ReadBytes(chunkSize); // skip unknown chunk

                    }

                }


                // 3. Find 'data' subchunk

                while (true)

                {

                    string chunkId = new string(reader.ReadChars(4));

                    int chunkSize = reader.ReadInt32();

                    if (chunkId == "data")

                    {

                        int bytesPerSample = bitsPerSample / 8;

                        int totalSamples = chunkSize / bytesPerSample;

                        var amplitudes = new List<float>();


                        for (int i = 0; i < totalSamples; i++)

                        {

                            if (reader.BaseStream.Position + bytesPerSample > reader.BaseStream.Length)

                                break;


                            short sample = reader.ReadInt16();

                            float norm = sample / 32768f;

                            amplitudes.Add(norm);


                            if (channels == 2)

                                reader.ReadInt16(); // skip right channel

                        }


                        // 4. Resample if needed

                        if (sampleRate != 8000)

                        {

                            var resampled = new List<float>();

                            double factor = sampleRate / 8000.0;

                            for (int i = 0; i < amplitudes.Count / factor; i++)

                            {

                                double idx = i * factor;

                                int i0 = (int)idx;

                                double frac = idx - i0;

                                float val = (i0 + 1 < amplitudes.Count)

                                    ? (float)((1 - frac) * amplitudes[i0] + frac * amplitudes[i0 + 1])

                                    : amplitudes[i0];

                                resampled.Add(val);

                            }

                            amplitudes = resampled;

                        }
















                        // 5. Save GTAMPS

                          File.WriteAllLines(outputGtampsPath, amplitudes.Select(a => a.ToString("F8")));

                           Console.WriteLine($"Saved GTAMPS: {outputGtampsPath}");


                        System.Windows.Forms.MessageBox.Show($"Saved GTAMPS: {outputGtampsPath}   amplitudes =  {amplitudes}");














                       //     string outputGtampsPath_generated = wavPath + "_actual_sampleRate=" + sampleRate + "_actual_bps=" + bitsPerSample + "_numSamples=" + numSamples + "_smpls=" + samples + "_8000Hz_16_bits_pcms_" + ".GTAMPS";

                       //samples

                       // Save as .GTAMPS

                       //   File.WriteAllLines(outputGtampsPath_generated, samples.Select(s => s.ToString("F8")));



                        return;

                    }

                    else

                    {

                        reader.ReadBytes(chunkSize); // skip unknown chunk

                    }

                }


                throw new Exception("Data chunk not found.");

            }

        }//public static void ConvertWavToGTAMPS___with_corrections_GPT(string wavPath, string outputGtampsPath)



        //////    public static void ConvertWavToGTAMPS___with_corrections_GPT(string wavPath, string outputGtampsPath)

        //////    {

        //////        using (var reader = new BinaryReader(File.OpenRead(wavPath)))

        //////        {

        //////            // 1. Read RIFF header

        //////            if (new string(reader.ReadChars(4)) != "RIFF")

        //////                throw new Exception("Not a valid RIFF file.");

        //////            reader.ReadInt32(); // File size

        //////            if (new string(reader.ReadChars(4)) != "WAVE")

        //////                throw new Exception("Not a valid WAVE file.");


        //////            // 2. Find 'fmt ' subchunk

        //////            short channels = 1;

        //////            int sampleRate = 8000;

        //////            short bitsPerSample = 16;

        //////            while (true)

        //////            {

        //////                string chunkId = new string(reader.ReadChars(4));

        //////                int chunkSize = reader.ReadInt32();


        //////                if (chunkId == "fmt ")

        //////                {

        //////                    short audioFormat = reader.ReadInt16();

        //////                    channels = reader.ReadInt16();

        //////                    sampleRate = reader.ReadInt32();

        //////                    reader.ReadInt32(); // byteRate

        //////                    reader.ReadInt16(); // blockAlign

        //////                    bitsPerSample = reader.ReadInt16();


        //////                    if (chunkSize > 16)

        //////                        reader.ReadBytes(chunkSize - 16); // skip extra fmt bytes

        //////                    break;

        //////                }

        //////                else

        //////                {

        //////                    reader.ReadBytes(chunkSize); // skip unknown chunk

        //////                }

        //////            }


        //////            // 3. Find 'data' subchunk

        //////            while (true)

        //////            {

        //////                string chunkId = new string(reader.ReadChars(4));

        //////                int chunkSize = reader.ReadInt32();

        //////                if (chunkId == "data")

        //////                {

        //////                    int bytesPerSample = bitsPerSample / 8;

        //////                    int totalSamples = chunkSize / bytesPerSample;

        //////                    var amplitudes = new List<float>();


        //////                    for (int i = 0; i < totalSamples; i++)

        //////                    {

        //////                        if (reader.BaseStream.Position + bytesPerSample > reader.BaseStream.Length)

        //////                        { break; }


        //////                        short sample = reader.ReadInt16();

        //////                        float norm = sample / 32768f;

        //////                        amplitudes.Add(norm);


        //////                        if (channels == 2)

        //////                        {

        //////                            reader.ReadInt16(); // skip right channel}

        //////                        }// for (int i = 0; i < totalSamples; i++)


        //////                        // 4. Resample if needed

        //////                        if (sampleRate != 8000)

        //////                    {

        //////                        var resampled = new List<float>();

        //////                        double factor = sampleRate / 8000.0;

        //////                        for (int rrr = 0; rrr < amplitudes.Count / factor; rrr++)

        //////                        {

        //////                            double idx = rrr * factor;

        //////                            int i0 = (int)idx;

        //////                            double frac = idx - i0;

        //////                            float val = (i0 + 1 < amplitudes.Count)

        //////                                ? (float)((1 - frac) * amplitudes[i0] + frac * amplitudes[i0 + 1])

        //////                                : amplitudes[i0];

        //////                            resampled.Add(val);

        //////                        }//for (int rrr = 0; rrr < amplitudes.Count / factor; rrr++)

        //////                        amplitudes = resampled;

        //////                    }//if (sampleRate != 8000)


        //////                    // 5. Save GTAMPS

        //////                    //   File.WriteAllLines(outputGtampsPath, amplitudes.Select(a => a.ToString("F8")));

        //////                    //   Console.WriteLine($"Saved GTAMPS: {outputGtampsPath}");
















        //////                    string outputGtampsPath_generated = wavPath + "_actual_sampleRate=" + sampleRate + "_actual_bps=" + bitsPerSample + "_numSamples=" + numSamples + "_smpls=" + samples + "_8000Hz_16_bits_pcms_" + ".GTAMPS";

        //////                    //samples

        //////                    // Save as .GTAMPS

        //////                    File.WriteAllLines(outputGtampsPath_generated, samples.Select(s => s.ToString("F8")));



        //////                    return;

        //////                }

        //////                else

        //////                {

        //////                    reader.ReadBytes(chunkSize); // skip unknown chunk

        //////                }

        //////            }


        //////            throw new Exception("Data chunk not found.");

        //////        }

        //////    }//public static void ConvertWavToGTAMPS___with_corrections_GPT(string wavPath, string outputGtampsPath)



        //////    public static void ConvertANY_KIND_OF_WavToGTAMPS(string wavPath, string outputGtampsPath)

        //////    {

        //////        using (var reader = new BinaryReader(File.OpenRead(wavPath)))

        //////        {

        //////            // Read RIFF header

        //////            string riff = new string(reader.ReadChars(4));

        //////            int fileSize = reader.ReadInt32();

        //////            string wave = new string(reader.ReadChars(4));


        //////            // Read format chunk

        //////            string fmt = new string(reader.ReadChars(4));

        //////            int fmtSize = reader.ReadInt32();

        //////            short audioFormat = reader.ReadInt16();

        //////            short channels = reader.ReadInt16();

        //////            int sampleRate = reader.ReadInt32();

        //////            int byteRate = reader.ReadInt32();

        //////            short blockAlign = reader.ReadInt16();

        //////            short bitsPerSample = reader.ReadInt16();


        //////            // Skip any extra bytes if fmt chunk > 16

        //////            if (fmtSize > 16)

        //////            { reader.ReadBytes(fmtSize - 16); }


        //////            // Seek to data chunk

        //////            while (new string(reader.ReadChars(4)) != "data")

        //////            {

        //////                reader.BaseStream.Position -= 3;

        //////            }//while (new string(reader.ReadChars(4)) != "data")








        //////            int dataSize = reader.ReadInt32();


        //////            int numSamples = dataSize / (bitsPerSample / 8);

        //////            var samples = new List<float>(numSamples);


        //////            for (int i = 0; i < numSamples; i++)

        //////            {

        //////                short sample16 = reader.ReadInt16();

        //////                float normalized = sample16 / 32768f;

        //////                samples.Add(normalized);

        //////                if (channels == 2) reader.ReadInt16(); // Skip second channel if stereo

        //////            }//for (int i = 0; i < numSamples; i++)


        //////            // Resample if needed (e.g., from 44100Hz to 8000Hz)

        //////            if (sampleRate != 8000)

        //////            {

        //////                var resampled = new List<float>();

        //////                double factor = sampleRate / 8000.0;



        //////                for (int i = 0; i < samples.Count / factor; i++)

        //////                {

        //////                    double index = i * factor;

        //////                    int idx = (int)index;

        //////                    double frac = index - idx;

        //////                    float sample = (idx + 1 < samples.Count)

        //////                        ? (float)((1 - frac) * samples[idx] + frac * samples[idx + 1])

        //////                        : samples[idx];

        //////                    resampled.Add(sample);

        //////                }//for (int i = 0; i < samples.Count / factor; i++)

        //////                samples = resampled;

        //////            }//if (sampleRate != 8000)


        //////           string  outputGtampsPath_generated= wavPath+ "_actual_sampleRate=" + sampleRate + "_actual_bps="+ bitsPerSample + "_numSamples=" + numSamples + "_smpls="+ samples+ "_8000Hz_16_bits_pcms_" + ".GTAMPS";

        //////            //samples

        //////            // Save as .GTAMPS

        //////            File.WriteAllLines(outputGtampsPath_generated, samples.Select(s => s.ToString("F8")));

        //////            // Console.WriteLine($"Saved GTAMPS to: {outputGtampsPath}");


        //////            System.Windows.Forms.MessageBox.Show($"Saved GTAMPS to: {outputGtampsPath}");

        //////        }//using (var reader = new BinaryReader(File.OpenRead(wavPath)))














        //////    }//public static void ConvertWavToGTAMPS(string wavPath, string outputGtampsPath)


    }// public class SAANS_NO_3RD_PARTY_GPT_STYLES_WAV_FILES_READER_TO_GENERATE_8000_HZ_16_BIT_PCMS_GTAMPS


    public class WavGenerator___44_SHRUTIS_BACKWARD_TO_FORWARDS_Reads_GTAMPS_MONO_8000_Hz_Samples_16_bits_no_3rd_party_apis

    {

        const int SampleRate = 8000;

        const int BitsPerSample = 16;

        const int Channels = 1;

        const double Pi = Math.PI;



 


        public static void SAANS___44_SAMPLES_WavGenerator___Reads_GTAMPS_MONO_8000_Hz_Samples_16_bits_no_3rd_party_apis___Main(string gtamps_filesnames)

        {

            string inputPath = gtamps_filesnames;// "your_file_path_here.txt";



            // Read float samples

            var samples = File.ReadLines(inputPath)

                              .Where(line => double.TryParse(line, out _))

                              .Select(double.Parse)

                              .ToList();


            var allShifted = new List<short>();


            for (int r = 1; r <= 22; r++)

            {

                double shiftFactor = Math.Pow(2, r / 22.0);

                var shifted = ResampleWithFrequencyShift(samples, shiftFactor);

                allShifted.AddRange(shifted);

            }//for (int r = 1; r <= 22; r++)




            for (int r = -22; r <= 0; r++)

            {

                double shiftFactor = Math.Pow(2, r / 22.0);

                var shifted = ResampleWithFrequencyShift(samples, shiftFactor);

                allShifted.AddRange(shifted);

            }//for (int r = -22; r <= 0; r++)





            string outputPath = inputPath + "___44_SCALES_8000hZ_16_BITS_PCMS_" + allShifted.Count.ToString() + "_output.wav";


            WriteWavFile(outputPath, allShifted);

            Console.WriteLine("WAV file written to: " + outputPath);

        }//public static void SAANS___44_SAMPLES_WavGenerator___Reads_GTAMPS_MONO_8000_Hz_Samples_16_bits_no_3rd_party_apis___Main(STRING gtamps_filesnames)


        public static List<short> ResampleWithFrequencyShift(List<double> samples, double shiftFactor)

        {

            int newLength = (int)(samples.Count / shiftFactor);

            var shifted = new List<short>(newLength);


            for (int i = 0; i < newLength; i++)

            {

                double srcIndex = i * shiftFactor;

                int idx = (int)srcIndex;

                double frac = srcIndex - idx;


                double value = 0;

                if (idx + 1 < samples.Count)

                    value = (1 - frac) * samples[idx] + frac * samples[idx + 1];

                else if (idx < samples.Count)

                    value = samples[idx];


                short pcmVal = (short)(value * short.MaxValue);

                shifted.Add(pcmVal);

            }//for (int i = 0; i < newLength; i++)


            return shifted;

        }//public static List<short> ResampleWithFrequencyShift(List<double> samples, double shiftFactor)


        public static void WriteWavFile(string filePath, List<short> samples)

        {

            using (var stream = new FileStream(filePath, FileMode.Create))

            using (var writer = new BinaryWriter(stream))

            {

                int byteRate = SampleRate * Channels * BitsPerSample / 8;

                int dataSize = samples.Count * BitsPerSample / 8;


                // RIFF header

                writer.Write(Encoding.ASCII.GetBytes("RIFF"));

                writer.Write(36 + dataSize);

                writer.Write(Encoding.ASCII.GetBytes("WAVE"));


                // fmt subchunk

                writer.Write(Encoding.ASCII.GetBytes("fmt "));

                writer.Write(16); // PCM

                writer.Write((short)1); // AudioFormat = PCM

                writer.Write((short)Channels);

                writer.Write(SampleRate);

                writer.Write(byteRate);

                writer.Write((short)(Channels * BitsPerSample / 8));

                writer.Write((short)BitsPerSample);


                // data subchunk

                writer.Write(Encoding.ASCII.GetBytes("data"));

                writer.Write(dataSize);

                foreach (short s in samples)

                { writer.Write(s); }

            }//using (var writer = new BinaryWriter(stream))

        }//public static void WriteWavFile(string filePath, List<short> samples)

    }// public class WavGenerator___44_SHRUTIS_BACKWARD_TO_FORWARDS_Reads_GTAMPS_MONO_8000_Hz_Samples_16_bits_no_3rd_party_apis




    




    /// <summary>

    /// /////////////////////////////////////////////////////////////////////////////////////

    /// </summary>



    public class WavGenerator___Reads_GTAMPS_MONO_8000_Hz_Samples_16_bits_no_3rd_party_apis

    {

        const int SampleRate = 8000;

        const int BitsPerSample = 16;

        const int Channels = 1;

        const double Pi = Math.PI;


        public static void SAANS___WavGenerator___Reads_GTAMPS_MONO_8000_Hz_Samples_16_bits_no_3rd_party_apis___Main(string gtamps_filesnames)

        {

            string inputPath = gtamps_filesnames;// "your_file_path_here.txt";

           


            // Read float samples

            var samples = File.ReadLines(inputPath)

                              .Where(line => double.TryParse(line, out _))

                              .Select(double.Parse)

                              .ToList();


            var allShifted = new List<short>();


            for (int r = 1; r <= 22; r++)

            {

                double shiftFactor = Math.Pow(2, r / 22.0);

                var shifted = ResampleWithFrequencyShift(samples, shiftFactor);

                allShifted.AddRange(shifted);

            }//for (int r = 1; r <= 22; r++)



            string outputPath = inputPath + "___22_times_8000hZ_16_BITS_PCMS_"+allShifted.Count.ToString() + "_output.wav";


            WriteWavFile(outputPath, allShifted);

            Console.WriteLine("WAV file written to: " + outputPath);

        }//public static void SAANS___WavGenerator___Reads_GTAMPS_MONO_8000_Hz_Samples_16_bits_no_3rd_party_apis___Main(STRING gtamps_filesnames)


        public static List<short> ResampleWithFrequencyShift(List<double> samples, double shiftFactor)

        {

            int newLength = (int)(samples.Count / shiftFactor);

            var shifted = new List<short>(newLength);


            for (int i = 0; i < newLength; i++)

            {

                double srcIndex = i * shiftFactor;

                int idx = (int)srcIndex;

                double frac = srcIndex - idx;


                double value = 0;

                if (idx + 1 < samples.Count)

                    value = (1 - frac) * samples[idx] + frac * samples[idx + 1];

                else if (idx < samples.Count)

                    value = samples[idx];


                short pcmVal = (short)(value * short.MaxValue);

                shifted.Add(pcmVal);

            }//for (int i = 0; i < newLength; i++)


            return shifted;

        }//public static List<short> ResampleWithFrequencyShift(List<double> samples, double shiftFactor)


        public static void WriteWavFile(string filePath, List<short> samples)

        {

            using (var stream = new FileStream(filePath, FileMode.Create))

            using (var writer = new BinaryWriter(stream))

            {

                int byteRate = SampleRate * Channels * BitsPerSample / 8;

                int dataSize = samples.Count * BitsPerSample / 8;


                // RIFF header

                writer.Write(Encoding.ASCII.GetBytes("RIFF"));

                writer.Write(36 + dataSize);

                writer.Write(Encoding.ASCII.GetBytes("WAVE"));


                // fmt subchunk

                writer.Write(Encoding.ASCII.GetBytes("fmt "));

                writer.Write(16); // PCM

                writer.Write((short)1); // AudioFormat = PCM

                writer.Write((short)Channels);

                writer.Write(SampleRate);

                writer.Write(byteRate);

                writer.Write((short)(Channels * BitsPerSample / 8));

                writer.Write((short)BitsPerSample);


                // data subchunk

                writer.Write(Encoding.ASCII.GetBytes("data"));

                writer.Write(dataSize);

                foreach (short s in samples)

                { writer.Write(s); }

            }//using (var writer = new BinaryWriter(stream))

        }//public static void WriteWavFile(string filePath, List<short> samples)

    }//public class WavGenerator___Reads_GTAMPS_MONO_8000_Hz_Samples_16_bits_no_3rd_party_apis







}//namespace SAAN_FRESH___RAW_NON_APIS_WAVES_TO_SHRUTIES_COPIER_GPTS