void Start()
 {
     soundGen = GameObject.Find("Audio").GetComponent <SoundGenerator>();
     calculateAlternatingCurrent();
     calculateUwy();
     soundGen.setValues(440 + Uwy);
 }
Exemple #2
0
 private byte[] GenerateMp3(Song song)
 {
     if (song.Notes == null)
     {
         return(null);
     }
     using (var generatedSongStream = new MemoryStream())
     {
         var mp3File  = new MemoryStream();
         var waveFile = new WaveFile(22050, BitDepth.Bit16, 1, generatedSongStream);
         var sg       = new SoundGenerator(waveFile);
         foreach (var note in song.Notes)
         {
             sg.AddSimpleTone(note.Frequency, note.Duration);
         }
         sg.Save();
         generatedSongStream.Position = 0;
         var r  = new WaveFileReader(generatedSongStream);
         var wr = new LameMP3FileWriter(mp3File, r.WaveFormat, 96);
         r.CopyTo(wr);
         wr.Flush();
         var fileData = mp3File.ToArray();
         mp3File.Dispose();
         r.Dispose();
         wr.Dispose();
         return(fileData);
     }
 }
Exemple #3
0
        private static void DoGenerateaveWithSquareOscillator()
        {
            const int    sampleRate = 44100;
            const string partition  =
                "16#d1 32f1 32f1 16f1 8f1 16#d1 16#d1 16#d1 16#d1 32#f1 32#f1 16#f1 8#f1 16f1 16f1 16f1 16#d1 32f1 32f1 16f1 8f1 16#d1 16#d1 16#d1 16#d1 32#f1 32#f1 16#f1 8#f1 16f1 16e1 16#d1 16#d2 2d2 16#a1 16#g1 2#a1";
            const int tempo = 20;

            var fullpath = Path.ChangeExtension(Path.GetTempFileName(), "wav");

            var oscillator     = new SawToothOccilator(sampleRate);
            var soundGenerator = new SoundGenerator(oscillator);

            var tuneReader = new TuneReader();
            var tune       = tuneReader.Read(partition, tempo);

            soundGenerator.SaveToWaveFile(fullpath, tune);

            System.Console.WriteLine(fullpath);

            System.Console.ReadLine();

            //var data = new List<double>();
            //tune.TuneElementList.Cast<pitch>().Select(s => s.NoteFrequence.Frequence).ToList().ForEach(e =>
            //{
            //    oscillator.SetFrequency(e);
            //    for (int i = 0; i < sampleRate; i++)
            //        data.Add(oscillator.GetNext(i));
            //});

            //SoundGenerator.SaveIntoStream(data.ToArray(), data.Count(), sampleRate);
        }
Exemple #4
0
        static void Main(string[] args)
        {
            try
            {
                double frequence = 0, amplitude = 0;

                int durability = 0;

                string filename = String.Empty;

                Console.WriteLine("Enter the durability");
                durability = Convert.ToInt32(Console.ReadLine());

                Console.WriteLine("Enter the frequence");
                frequence = Convert.ToDouble(Console.ReadLine());

                Console.WriteLine("Enter the amplitude");
                amplitude = Convert.ToDouble(Console.ReadLine());


                Console.WriteLine("Enter the filename:");
                filename = Convert.ToString(Console.ReadLine());


                SoundGenerator generator = new SoundGenerator(durability, frequence, amplitude);


                generator.Save(absolute + filename + ".wav");
            }
            catch
            {
                Console.WriteLine("Error has occured");
            }
        }
Exemple #5
0
    // Start is called before the first frame update
    void Start()
    {
        source = GetComponent <AudioSource>();
        if (source == null)
        {
            Debug.LogWarning("Did not find an Audio Source component on this GameObject. This script will probably die.");
        }

        if (SoundToPlay != null)
        {
            return; //We're done here.
        }
        // if not, we'll need to pick up a sound from the Sound Generator. We can either define one beforehand or find the (hopefully only) one in the scene.
        // If we don't have one already
        if (soundGenerator == null)
        {
            soundGenerator = FindObjectOfType <SoundGenerator>();
            if (soundGenerator == null) //whoops guess no sound then
            {
                Debug.LogWarning("Can't find a sound to play. No Sound Generator available. I hope you like the silence.");
                return;
            }
        }
        // yayy we got one
        SoundToPlay = soundGenerator.GetRandomSound();
    }
        public static string Generate(string melody)
        {
            SimueCompiler compiler = new SimueCompiler();
            var           result   = compiler.Parse(compiler.Tokenize(melody));

            if (result.Errors.Count != 0)
            {
                var ex = new ArgumentException("Incorrect notation");
                ex.Data.Add("Error", GenerationError.IncorrectNotation);
                throw ex;
            }
            if (result.Song.Length > MelodyGeneration.LengthLimit)
            {
                var ex = new ArgumentException("The melody is too long.");
                ex.Data.Add("Error", GenerationError.TooLong);
                throw ex;
            }
            MemoryStream   fileStream = new MemoryStream();
            WaveFile       melodyFile = new WaveFile(Samplerate, Bitness, Channels, fileStream);
            SoundGenerator generator  = new SoundGenerator(melodyFile);

            generator.Volume = 0.3;
            Song song = result.Song;

            //Generation
            foreach (var note in song.Notes)
            {
                generator.AddSimpleTone(note.Frequency, note.Duration);
            }
            generator.Save();
            fileStream.Position = 0;
            string dataUrl = string.Format("data:audio/wav;base64,{0}", Convert.ToBase64String(fileStream.ToArray()));

            return(dataUrl);
        }
Exemple #7
0
        public Form1()
        {
            InitializeComponent();

            serializer     = new RttlConverter();
            oscillator     = new SawToothOccilator(sampleRate);
            soundGenerator = new SoundGenerator(oscillator);
        }
        public App()
        {
            MainWindow     mainWindow          = new MainWindow();
            SoundGenerator soundGenerator      = new SoundGenerator();
            MainWindowVM   mainWindowViewModel = new MainWindowVM(soundGenerator);

            mainWindow.DataContext = mainWindowViewModel;
            mainWindow.Show();
        }
Exemple #9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MMLPlayer"/> class.
 /// </summary>
 public MMLPlayer()
 {
     midiOut = new SoundGenerator();
     for (int i = 0; i < channels.Length; i++)
     {
         channels[i] = new MMLChannel(i, GetNoteTime, ChangeTempo, midiOut.ChangeDuty, midiOut.Send, midiOut.ChangeMode, midiOut.EnableEnvelope);
     }
     ResetChannels();
 }
Exemple #10
0
        public static TimeSpan TestChirp(SoundGenerator sg)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();
            sg.AddSimpleTone(440, 2000, false);
            sg.AddSineChirp(440, 900, 3000);
            sg.AddSimpleTone(900, 2000, false);
            sw.Stop();
            return(sw.Elapsed);
        }
Exemple #11
0
 private void PlayerFinishedLevel()
 {
     if (!playerFinishedLevel)
     {
         SoundGenerator soundGenerator = GameObject
                                         .FindGameObjectsWithTag("MusicGenerator")[0]
                                         .GetComponent <SoundGenerator>();
         soundGenerator.PlayLevelFinished();
         playerFinishedLevel = true;
     }
 }
        static void Main()
        {
            List <SoundFragment> sound = new List <SoundFragment>();

            sound.Add(new SoundFragment(440, 2.5f));
            sound.Add(new SoundFragment(700, 2.5f));
            sound.Add(new SoundFragment(440, 3.5f));
            SoundGenerator waveGenerator = new SoundGenerator(sound);

            waveGenerator.Save("./test.wav");
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new SoundProcessing());
        }
Exemple #13
0
        public static void Run(TestMethod test, string testName)
        {
            FileStream file = new FileStream(
                Path.Combine(TestResultDir, string.Format("{0} {1}.wav", testName, Timestamp)),
                FileMode.Create);
            WaveFile       wavefile = new WaveFile(44100, BitDepth.Bit24, 1, file);
            SoundGenerator sg       = new SoundGenerator(wavefile);
            TimeSpan       time     = test(sg);

            sg.Save();
            file.Close();
            file.Dispose();
            Console.WriteLine("Done. {0} Elapsed time: {1}", testName, time.ToString(@"hh\:mm\:ss\.fff"));
        }
Exemple #14
0
        public static void TestSimple()
        {
            FileStream file = new FileStream(
                Path.Combine(TestResultDir, string.Format("{0} {1}.wav", "Simple tone generation test", Timestamp)),
                FileMode.Create);
            WaveFile       wavefile = new WaveFile(44100, BitDepth.Bit32, 2, file);
            SoundGenerator sg       = new SoundGenerator(wavefile);

            sg.AddSimpleTone(440, 1000);
            sg.Save();
            file.Close();
            file.Dispose();
            Console.WriteLine("Simple tone generation test.");
        }
    public static CharacterAudio Create(GameObject gameObject, string soundGeneratorName = "DEFAULT")
    {
        var component = gameObject.AddComponent <CharacterAudio>();

        var soundGenerators = new SoundGenerator[8];

        for (var i = 0; i < soundGenerators.Length; i++)
        {
            soundGenerators[i] = global::SoundGenerator.Get(soundGeneratorName, i);
        }

        component.soundGenerators = soundGenerators;

        return(component);
    }
Exemple #16
0
        public static TimeSpan TestFade(SoundGenerator sg)
        {
            Stopwatch sw          = new Stopwatch();
            Random    r           = new Random();
            int       n           = 100;
            var       frequencies = Enumerable.Repeat(1, n).Select(frequency => frequency * r.Next(400, 1000)).ToArray();

            sw.Start();
            for (int i = 0; i < n; i++)
            {
                sg.AddSimpleTone(frequencies[i], 300, true);
            }
            sw.Stop();
            return(sw.Elapsed);
        }
    IEnumerator MusicRoomEvent_()
    {
        sceneEventSystem.DirectMode();
        Camera.main.GetComponent <CameraMove>().SetTarget(musicRoomZombies[0].transform.position);
        yield return(new WaitForSeconds(3f));

        Camera.main.GetComponent <CameraMove>().SetTarget(sceneEventSystem.Player);
        sceneEventSystem.DirectMode();

        yield return(new WaitUntil(() => musicRoomStorageDoor.IsUnlocked));

        sceneEventSystem.MonologueBubbles(sceneEventSystem.Player, "빠루 끝을 문 사이에 넣고 힘을 줘서 문을 뜯어냈다.", 2);
        yield return(new WaitForSeconds(2f));

        SoundGenerator.SpreadSound(new Sound(9999, 350), musicRoomStorageDoor.transform.position); // 음악실 문을 따고 소음 발생
    }
Exemple #18
0
        public static void TestComplex()
        {
            FileStream file = new FileStream(
                Path.Combine(TestResultDir, string.Format("{0} {1}.wav", "Complex tone generation test", Timestamp)),
                FileMode.Create);
            WaveFile       wavefile = new WaveFile(44100, BitDepth.Bit32, 2, file);
            SoundGenerator sg       = new SoundGenerator(wavefile);

            for (int i = 0; i < 100; i++)
            {
                sg.AddComplexTone(r.Next(100, 500), false, 261.63, 329.63, 392);
            }
            sg.Save();
            file.Close();
            file.Dispose();
            Console.WriteLine("Complex tone generation test.");
        }
Exemple #19
0
        public static TimeSpan TestLoran(SoundGenerator sg)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();
            string sounds = "1180 128;1180 128;1180 128;1180 128;1180 128;1115 128;1115 128;1180 128;1180 128;1115 128;1180 128;1115 128;1180 128";

            string[] separate = sounds.Split(';');
            foreach (string sound in separate)
            {
                string[] note = sound.Split(' ');
                int      f    = int.Parse(note[0]);
                int      d    = int.Parse(note[1]);
                sg.AddSimpleTone(f, d, false);
            }
            sw.Stop();
            return(sw.Elapsed);
        }
Exemple #20
0
        static void Main(string[] args)
        {
            Data data1 = new Data(1, 2, 0, 0);
            Data data2 = new Data(1, 50, 0, 0.9);

            Signal signal1 = new SinusSignal(data1);
            Signal signal2 = new ImpulseSignal(data2);


            var values = Modulation.ApplyFM(signal1, signal2, SampleRate, Seconds);

            SoundGenerator soundGenerator = new SoundGenerator(SampleRate, Seconds,
                                                               $"MS {signal1.GetType()} A {data1.Amplitude} F {data1.Frequency} phi0 {data1.StartPhase} D {data1.DutyFactor}. " +
                                                               $"CS {signal2.GetType()} A {data2.Amplitude} F {data2.Frequency} phi0 {data2.StartPhase} D {data2.DutyFactor}"
                                                               );

            soundGenerator.Generate(values, true);
        }
Exemple #21
0
        public static TimeSpan TestRandomChirp(SoundGenerator sg)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();
            double f1 = 0;
            double f2 = 440;
            Random r  = new Random();

            for (int i = 0; i < 100; i++)
            {
                f1 = f2;
                f2 = r.Next(300, 4000);
                sg.AddSineChirp(f1, f2, 300);
            }
            sg.AddSimpleTone(f2, 2000, false);
            sw.Stop();
            return(sw.Elapsed);
        }
Exemple #22
0
        private static void DoParseRttlString()
        {
            const int    sampleRate   = 44100;
            const string rttlString   = "TocattaFugue:d=32,o=5,b=100:a#.,g#.,2a#,g#,f#,f,d#.,4d.,2d#,a#.,g#.,2a#,8f,8f#,8d,2d#,8d,8f,8g#,8b,8d6,4f6,4g#.,4f.,1g,32p,";
            var          deserializer = new RttlSerializer();
            var          tune         = deserializer.Deserialize(rttlString);

            var fullpath = Path.ChangeExtension(Path.GetTempFileName(), "wav");

            var oscillator     = new SawToothOccilator(sampleRate);
            var soundGenerator = new SoundGenerator(oscillator);

            tune.Tempo = 25;

            soundGenerator.SaveToWaveFile(fullpath, tune);

            System.Console.WriteLine(fullpath);

            System.Console.ReadLine();
        }
    IEnumerator SchoolOfficeEvent_()
    {
        sceneEventSystem.DirectMode();
        Camera.main.GetComponent <CameraMove>().SetTarget(tvSoundSource);
        schoolOfficeStorageDoor.IsUnlocked = true;
        schoolOfficeStorageDoor.BehaviorByInteraction(null);
        yield return(new WaitForSeconds(0.5f));

        SoundGenerator.SpreadSound(new Sound(9999, 50), tvSoundSource.transform.position); // 좀비들 tv 근처로 우르르 몰려나옴

        yield return(new WaitForSeconds(3));

        Camera.main.GetComponent <CameraMove>().SetTarget(sceneEventSystem.Player);
        sceneEventSystem.DirectMode();

        while (true)
        {
            yield return(waitTime);

            if (tv.IsOn)
            {
                SoundGenerator.SpreadSound(new Sound(9999, 50), tvSoundSource.transform.position); // tv 켜진 후 소음 발생
                tvScreen.GetComponent <MeshRenderer>().materials[0].color = Color.white;
                for (int i = 0; i < schoolOfficeStorageZombies.Count; i++)                         // 좀비들의 어그로 조정
                {
                    schoolOfficeStorageZombies[i].GetComponent <EnemyProperty>().ToRunRadius = 0;
                }
            }
            else
            {
                tvScreen.GetComponent <MeshRenderer>().materials[0].color = Color.black;
                for (int i = 0; i < schoolOfficeStorageZombies.Count; i++) // 좀비들의 어그로 조정
                {
                    schoolOfficeStorageZombies[i].GetComponent <EnemyProperty>().ToRunRadius = 350;
                }
            }
        }
    }
Exemple #24
0
    void UpdateByState()
    {
        SoundGenerator.SpreadSound(sounds[(int)property.State], transform.position); // 프로파일러 확인 결과 가비지 발생하는 코드임. 추후에 수정해야할 필요가 있음.
        switch (property.State)
        {
        case PlayerState.Idle:
        {
            movespeed = 0;
            animator.SetInteger("State", (int)PlayerAnimation.Idle);
            AudioManager.Instance.StopStepSound();
            break;
        }

        case PlayerState.Sneak:
        {
            movespeed = property.SneakSpeed;
            animator.SetInteger("State", (int)PlayerAnimation.Move);
            AudioManager.Instance.PlayStepSound("Sneak");
            break;
        }

        case PlayerState.Walk:
        {
            movespeed = property.WalkSpeed;
            animator.SetInteger("State", (int)PlayerAnimation.Move);
            AudioManager.Instance.PlayStepSound("Walk1");
            break;
        }

        case PlayerState.Run:
        {
            movespeed = property.RunSpeed;
            animator.SetInteger("State", (int)PlayerAnimation.Run);
            AudioManager.Instance.PlayStepSound("Run1");
            break;
        }
        }
    }
Exemple #25
0
        // Update is called once per frame
        protected void Update()
        {
            if (!levelCompleted)
            {
                UserInput userInput = input.GetInput();

                if (CharacterCoinController.CoinCount > 100)
                {
                    coinController.Reset();
                    character.AddLives(1);
                }

                if (character.IsDead & !characterDied)
                {
                    SoundGenerator soundGenerator = GameObject
                                                    .FindGameObjectsWithTag("MusicGenerator")[0]
                                                    .GetComponent <SoundGenerator>();

                    if (character.Health <= 0)
                    {
                        soundGenerator.PlayPlayerIsDead(true);
                    }
                    else
                    {
                        soundGenerator.PlayPlayerIsDead();
                    }

                    if (cameraController != null)
                    {
                        Destroy(this.cameraController);
                    }

                    characterDied = true;
                }

                character.Move(userInput.move, userInput.status);
            }
        }
Exemple #26
0
    private IEnumerator ElectricShock()
    {
        while (true && zombie.activeInHierarchy)
        {
            yield return(null);

            if (Vector3.Distance(zombie.transform.position, transform.position) < 15)
            {
                Camera.main.GetComponent <CameraMove>().SetTarget(zombie);
                sceneEventSystem.Player.GetComponent <PlayerInput>().enabled = false;
                sceneEventSystem.Player.transform.GetChild(0).GetComponent <Animator>().SetInteger("State", 0);
                sceneEventSystem.DirectMode();
                GameObject.Find("Canvas").transform.GetChild(0).GetChild(2).GetChild(0).GetComponent <Joystick>().OnPointerUp(null);
                yield return(new WaitForSeconds(0.5f));

                zombie.GetComponent <EnemyProperty>().ToRunRadius       = 0;
                zombie.GetComponent <EnemyProperty>().RunToAttackRadius = 0;
                zombie.GetComponent <EnemyProperty>().RunToIdleRadius   = 0;
                yield return(new WaitForSeconds(1));

                SoundGenerator.SpreadSound(new Sound(9999, 30f), transform.position + new Vector3(0, 0, -2));
                yield return(new WaitForSeconds(3f));

                AudioManager.Instance.PlaySoundOneShot("ZombieAttack", 2);
                zombie.GetComponent <Enemy>().AnimatorActiveCheck(EnemyAnimation.Attack);
                yield return(new WaitForSeconds(1.5f));

                Camera.main.GetComponent <CameraMove>().SetTarget(sceneEventSystem.Player);
                yield return(StartCoroutine(Boom()));

                yield return(StartCoroutine(KaTalk()));

                break;
            }

            //좀비의 타겟을 분전반으로 고정
        }
    }
Exemple #27
0
        private void F2()
        {
            saveFileName = "";
            NAudio.Wave.WaveChannel32 wave = new NAudio.Wave.WaveChannel32(new NAudio.Wave.WaveFileReader(readFile.FileName));

            byte[]         buffer         = new byte[16384];
            int            read           = 0;
            List <Complex> samplesComplex = new List <Complex>();
            List <int>     zeroFrequency  = new List <int>();

            while (wave.Position < wave.Length)
            {
                read = wave.Read(buffer, 0, 16384);
                for (int i = 0; i < read / 4; i++)
                {
                    samples.Add(BitConverter.ToSingle(buffer, i * 4));
                    samplesComplex.Add(new Complex(samples[i], 0));
                }
            }
            samplesComplex = CutSignalSamplesToPowerOfTwo(samplesComplex);
            List <List <Complex> > listOfFragments = new List <List <Complex> >();
            List <Complex>         fragment        = new List <Complex>();
            double totalValue = 0.0;
            double average    = 0.0;

            for (int i = 0; i < (samplesComplex.Count); ++i)
            {
                totalValue += samples[i];
            }
            average = Math.Abs(totalValue / samplesComplex.Count);
            for (int i = 0; i < samplesComplex.Count; i++)
            {
                if (Math.Abs(samples[i]) < average * 10)
                {
                    fragment.Add(new Complex(0.000000000001 * 0.5 * (1 - Math.Cos((2 * Math.PI * i) / (2048 - 1))), 0));
                }
                else
                {
                    fragment.Add(new Complex(samples[i] * 0.5 * (1 - Math.Cos((2 * Math.PI * i) / (2048 - 1))), 0));
                }
                chart3.Series["wave"].Points.Add(samples[i]);
                if (fragment.Count == 2048)
                {
                    listOfFragments.Add(fragment);
                    fragment = new List <Complex>();
                }
            }
            List <Complex> wCoefficients = CalculateWCoefficients(2048, false);

            for (int i = 0; i < listOfFragments.Count; ++i)
            {
                listOfFragments[i] = CalculateFastTransform(listOfFragments[i], wCoefficients, 0);
            }

            List <List <double> > amplitudeSpectrum = new List <List <double> >();

            for (int i = 0; i < listOfFragments.Count; ++i)
            {
                List <double> amplitude = new List <double>();
                for (int j = 0; j < listOfFragments[i].Count / 2; ++j)
                {
                    amplitude.Add(Math.Sqrt(listOfFragments[i][j].Real * listOfFragments[i][j].Real + listOfFragments[i][j].Imaginary * listOfFragments[i][j].Imaginary));
                }
                amplitudeSpectrum.Add(amplitude);
            }
            List <List <Complex> > spectrumComplex = new List <List <Complex> >();

            for (int i = 0; i < listOfFragments.Count; ++i)
            {
                List <Complex> spectrum = new List <Complex>();
                for (int j = 0; j < amplitudeSpectrum[i].Count; ++j)
                {
                    amplitudeSpectrum[i][j] = Math.Log(amplitudeSpectrum[i][j]);
                    spectrum.Add(new Complex(amplitudeSpectrum[i][j], 0));
                }
                spectrumComplex.Add(spectrum);
            }
            wCoefficients = CalculateWCoefficients(spectrumComplex[0].Count, false);
            for (int i = 0; i < listOfFragments.Count; ++i)
            {
                listOfFragments[i] = CalculateFastTransform(spectrumComplex[i], wCoefficients, 0);
            }
            List <List <double> > amplitudeSpectrum2 = new List <List <double> >();

            for (int i = 0; i < listOfFragments.Count; ++i)
            {
                List <double> spectrum = new List <double>();
                for (int j = 0; j < listOfFragments[i].Count / 2; ++j)
                {
                    spectrum.Add(Math.Sqrt(listOfFragments[i][j].Real * listOfFragments[i][j].Real + listOfFragments[i][j].Imaginary * listOfFragments[i][j].Imaginary));
                }
                amplitudeSpectrum2.Add(spectrum);
            }
            for (int i = 0; i < listOfFragments.Count; ++i)
            {
                double maxValue = amplitudeSpectrum2[i][treshhold - 1];
                int    maxIndex = treshhold - 1;
                for (int j = treshhold; j < amplitudeSpectrum2[i].Count; ++j)
                {
                    if (amplitudeSpectrum2[i][j] > maxValue)
                    {
                        maxValue = amplitudeSpectrum2[i][j];
                        maxIndex = j;
                    }
                }
                for (int k = 0; k < amplitudeSpectrum2[i].Count; ++k)
                {
                    chart4.Series["wave"].Points.Add(amplitudeSpectrum2[i][k]);
                }
                if (maxIndex == treshhold - 1)
                {
                    chart5.Series["wave"].Points.Add(0);
                    generatedSound.Add(new SoundFragment((int)(0), (2048f / 44100f) * 0.5f));
                }
                else
                {
                    chart5.Series["wave"].Points.Add(44100 / maxIndex);
                    generatedSound.Add(new SoundFragment((int)(44100 / maxIndex), (2048f / 44100f) * 0.5f));
                }
            }
            saveFile.Filter = "Wave File (*.wav)|*.wav;";
            if (saveFile.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            SoundGenerator waveGenerator = new SoundGenerator(generatedSound);

            waveGenerator.Save(saveFile.FileName);
            saveFileName    = saveFile.FileName;
            button2.Enabled = true;
            generatedSound  = new List <SoundFragment>();
        }
Exemple #28
0
 public SoundGeneratorService()
 {
     soundGenerator = new SoundGenerator(new SquareOscilator(44100));
 }
Exemple #29
0
        public SoundPlayer()
        {
            var oscillator = new SquareOscilator(44100);

            soundGenerator = new SoundGenerator(oscillator);
        }
Exemple #30
0
        private void T4()
        {
            saveFileName = "";
            NAudio.Wave.WaveChannel32 wave = new NAudio.Wave.WaveChannel32(new NAudio.Wave.WaveFileReader(readFile.FileName));

            byte[] buffer = new byte[44100];
            int    read   = 0;

            while (wave.Position < wave.Length)
            {
                read = wave.Read(buffer, 0, 44100);
                for (int i = 0; i < read / 4; i++)
                {
                    samples.Add(BitConverter.ToSingle(buffer, i * 4));
                }
            }
            List <List <double> > listOfFragments = new List <List <double> >();
            List <double>         fragment        = new List <double>();
            double totalValue = 0.0;
            double average    = 0.0;

            for (int i = 0; i < (samples.Count - samples.Count % 2048); ++i)
            {
                totalValue += samples[i];
            }
            average = Math.Abs(totalValue / samples.Count);
            for (int i = 0; i < (samples.Count - samples.Count % 2048); ++i)
            {
                if (Math.Abs(samples[i]) < average * 10)
                {
                    fragment.Add(0.00000001);
                }
                else
                {
                    fragment.Add(samples[i]);
                }
                chart3.Series["wave"].Points.Add(samples[i]);
                if (fragment.Count == 2048)
                {
                    listOfFragments.Add(fragment);
                    fragment = new List <double>();
                }
                chart3.Series["wave"].Points.Add(samples[i]);
            }

            List <List <double> > delayedSamples = new List <List <double> >();
            double previusValue;
            double actualValue;
            double nextValue;

            for (int i = 0; i < listOfFragments.Count; ++i)
            {
                List <double> delayed = new List <double>();
                for (int j = 0; j < listOfFragments[i].Count; ++j)
                {
                    double result = 0.0;
                    for (int k = 0; k < listOfFragments[i].Count; ++k)
                    {
                        if ((k + j) > (listOfFragments[i].Count - 1))
                        {
                            result += Math.Abs(listOfFragments[i][k]);
                        }
                        else
                        {
                            result += Math.Abs(listOfFragments[i][k] - listOfFragments[i][k + j]);
                        }
                    }
                    delayed.Add(result);
                    chart4.Series["wave"].Points.Add(delayed[j]);
                }
                delayedSamples.Add(delayed);
            }
            for (int i = 0; i < delayedSamples.Count; ++i)
            {
                int sampleNumber = 1;
                for (int j = 2; j < delayedSamples[i].Count; ++j)
                {
                    previusValue = delayedSamples[i][j - 2];
                    actualValue  = delayedSamples[i][j - 1];
                    nextValue    = delayedSamples[i][j];
                    if (actualValue < previusValue && actualValue < nextValue)
                    {
                        sampleNumber = j;
                        break;
                    }
                }
                for (int j = 0; j < delayedSamples[i].Count; ++j)
                {
                    if (sampleNumber == 1)
                    {
                        chart5.Series["wave"].Points.Add(0);
                    }
                    else
                    {
                        chart5.Series["wave"].Points.Add(44100 / sampleNumber * 2);
                    }
                    //chart5.Series["wave"].Points.Add(44100/sampleNumber * 2);
                }
                if (sampleNumber == 1)
                {
                    generatedSound.Add(new SoundFragment((int)(0), (2048f / 44100f) * 0.5f));
                }
                else
                {
                    generatedSound.Add(new SoundFragment((int)(44100 / sampleNumber * 2), (2048f / 44100f) * 0.5f));
                }
            }
            saveFile.Filter = "Wave File (*.wav)|*.wav;";
            if (saveFile.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            SoundGenerator waveGenerator = new SoundGenerator(generatedSound);

            waveGenerator.Save(saveFile.FileName);
            saveFileName    = saveFile.FileName;
            button2.Enabled = true;
            generatedSound  = new List <SoundFragment>();
        }