Ejemplo n.º 1
1
 public static void ProcessProvider(NAudio.Wave.ISampleProvider provider, string sourceName)
 {
     if (provider == null)
         return;
     float[] buffer = new float[1024];
     bool bContinue = true;
     int sampleRate = provider.WaveFormat.SampleRate;
     Decoders.MDC1200 mdc = new Decoders.MDC1200(sampleRate, MDCDelegate, sourceName);
     //Decoders.STAR star = new Decoders.STAR(sampleRate, null, RadioLog.AudioProcessing.Decoders.STAR.star_format.star_format_1_16383);
     while (bContinue)
     {
         int iCnt = provider.Read(buffer, 0, buffer.Length);
         bContinue = iCnt > 0;
         if (bContinue)
         {
             mdc.ProcessSamples(buffer, iCnt, true);
             //star.star_decoder_process_samples(buffer, iCnt);
         }
     }
 }
Ejemplo n.º 2
0
        private bool WinLose()
        {
            if (status == "win")
            {
                WindowPanelBuilder w = WindowPanelBuilder.Create(S.T("endGameWin"));
                w.panel.AddLabel(S.T("endGamePoints", points, S.Round().Round));
                w.panel.AddButtonT("endgame", () => { SceneManager.LoadScene(0); });
                w.panel.AddButtonT("endGameWinButton", () => { });
                w.Finish();
                NAudio.PlayMusic("win", false);
                status = null;
                return(true);
            }

            if (status == "lose")
            {
                WindowPanelBuilder w = WindowPanelBuilder.Create(S.T("endGameLose"));
                w.panel.AddLabel(S.T("endGamePoints", points, S.Round().Round));
                w.panel.AddButtonT("endgame", () =>
                {
                    w.Close();
                });
                w.onClose = () =>
                {
                    S.Players().KillPlayer(id);
                };
                w.Finish();
                NAudio.PlayMusic("lose", false);
                status = null;
                return(true);
            }

            return(false);
        }
Ejemplo n.º 3
0
 public static void AddButtonSound(Button g, string sound)
 {
     if (sound != null)
     {
         g.onClick.AddListener(() => { NAudio.Play(sound); });
     }
 }
Ejemplo n.º 4
0
        public void UpdatePanelOnMouse()
        {
            Vector2 p   = Camera.main.ScreenToWorldPoint(new Vector2(Input.mousePosition.x, Input.mousePosition.y));
            NVector pos = new NVector((int)p.x, (int)p.y, GameMgmt.Get().newMap.view.ActiveLevel);

            Debug.Log($"Click on {pos}");

            if (!pos.Valid())
            {
                NAudio.PlayBuzzer();
                return;
            }

            //active action?
            if (_action != null)
            {
                _action.Click(pos);
            }
            else
            {
                UpdatePanel(pos);
            }

            //center mouse?
            if (LSys.tem.options["centermouse"].Bool())
            {
                S.CameraMove().MoveTo(pos);
            }
        }
Ejemplo n.º 5
0
        public Toggle AddCheckbox(bool value, string title, UnityAction <bool> save, string audio = "checkBoxClick")
        {
            Toggle button = UIElements.CreateCheckBox(panel.transform, title, save).GetComponent <Toggle>();

            button.isOn = value;
            button.onValueChanged.AddListener((pos) => { NAudio.Play(audio); });
            return(button);
        }
Ejemplo n.º 6
0
 public void PlaySound(AudioClip clip, float volume, float pitch, float minDist, float maxDist)
 {
     audioSource.volume      = NAudio.RemapVolume(volume);
     audioSource.minDistance = minDist;
     audioSource.maxDistance = maxDist;
     audioSource.clip        = clip;
     audioSource.pitch       = pitch;
     audioSource.Play();
 }
Ejemplo n.º 7
0
        public Button CreateImageTextButton(Transform transform, Player player)
        {
            Button button = UIHelper.CreateImageTextButton(LSys.tem.inputs.GameButtonName(this), LClass.s.Button(id).Sprite(player), transform, () =>
            {
                NAudio.Play(Sound);
                Call(player);
            });

            return(button);
        }
Ejemplo n.º 8
0
 void CreateSources()
 {
     for (int i = 0; i < numberOfSources; i++)
     {
         AudioClip randomClip = clips[Random.Range(0, clips.Length)];
         var       source     = NAudio.CreateSource(null, randomClip);
         source.transform.position = Random.insideUnitSphere * range;
         source.PlayRandomTime();
     }
 }
Ejemplo n.º 9
0
        public void Call(Player player)
        {
            GameButton b = L.b.gameButtons[id];

            if (!b.req.Check(player))
            {
                NAudio.PlayBuzzer();
                UIHelper.ShowOk(b.Name(), b.req.Desc(player));
                return;
            }
            Run(player);
        }
Ejemplo n.º 10
0
        public virtual void ShowPanelMessageError(string text)
        {
            if (text == null)
            {
                ShowPanelMessage("");
                return;
            }

            infoText.color = Color.magenta;
            infoText.text  = text;
            NAudio.PlayBuzzer();
        }
Ejemplo n.º 11
0
        private void ShowDetail()
        {
            if (infoPanel.transform.childCount > 0)
            {
                UIHelper.ClearChild(infoPanel);
            }

            PanelBuilder p = PanelBuilder.Create(infoPanel.transform);

            selectedElement.ShowDetail(p);
            p.CalcSize();
            NAudio.Play(selectedElement.audioSwitch);
        }
Ejemplo n.º 12
0
        public void SetButtonText(string buttonText)
        {
            if (buttonText == null)
            {
                return;
            }

            selectButtonText = buttonText;
            selectButton     = UIHelper.CreateButton("Select an element first", buttonPanel.transform, () =>
            {
                NAudio.Play(selectedElement.audioPerform);
                selectedElement.Perform();
            }, null).GetComponent <Button>();
            selectButton.enabled = false;
        }
Ejemplo n.º 13
0
        public InputField AddInputRandom(string title, string def, UnityAction <string> save, Func <string> random)
        {
            InputField input = Instantiate(UIElements.Get().inputRandom, panel.transform);

            input.transform.GetChild(0).GetComponent <Text>().text = $"Enter {title}...";
            input.text = def;
            input.onValueChanged.AddListener(val => { save(val); });

            Button button = input.transform.GetChild(2).GetComponent <Button>();

            button.onClick.AddListener(() => { NAudio.Play("random"); });
            button.onClick.AddListener(() => { input.text = random(); });

            return(input);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Press the game button
        /// </summary>
        /// <param name="key"></param>
        private void PressGameButton(InputKey key)
        {
            GameButton gameButton = L.b.gameButtons[key.id];

            //check if possible to call
            if (!gameButton.req.Check(ActPlayer()))
            {
                OnMapUI.Get().ShowPanelMessageError(gameButton.req.Desc(ActPlayer()));
                return;
            }

            //call it
            NAudio.Play(gameButton.Sound);
            gameButton.Call(ActPlayer());
        }
Ejemplo n.º 15
0
    //float musicLowpass = 1;
    //float musicLowpassTarget = 1;
    //float musicLowpassVelo;

    private void Update()
    {
        musicVolume = Mathf.SmoothDamp(musicVolume, musicTarget, ref musicVelo, 1, 1000, 1.0f / 60f);
        float lowPass = Mathf.Lerp(200, 22000, musicVolume);

        //Debug.Log($"{musicVolume}, {musicTarget}");
        mixer.SetFloat("Music Volume", NAudio.GetLogVolume(musicVolume));
        mixer.SetFloat("Music Lowpass", lowPass);
        mixer.SetFloat("Diegetic Volume", NAudio.GetLogVolume(1 - musicVolume));

        if (showingCandleTut && Candle.e.isBurning)
        {
            showingCandleTut = false;
            DisableTut();
        }
    }
Ejemplo n.º 16
0
        IEnumerator LoadGame()
        {
            yield return(load.ShowMessage("Loading " + startConfig["file"]));

            yield return(load.ShowSubMessage($"Loading library"));

            L.b = ES3.Load <L>("lib", startConfig["file"] + "lib.9n");
            yield return(load.ShowSubMessage($"Loading file"));

            data = ES3.Load <GameData>("game", startConfig["file"] + "game.9n");

            ConnectGameObjs();

            //load Map
            yield return(newMap.LoadMap());

            yield return(load.ShowSubMessage($"Loading players"));

            yield return(data.players.GameLoaded());

            yield return(data.players.GameBegin());

            //load buildings
            yield return(load.ShowSubMessage($"Loading Buildings"));

            foreach (BuildingUnitData bdata in data.buildings.ToArray())
            {
                building.Load(bdata);
            }

            //load units
            yield return(load.ShowSubMessage($"Loading Units"));

            foreach (BuildingUnitData udata in data.units)
            {
                unit.Load(udata);
            }

            //init data
            gameRound.Load();

            //init players
            S.ActPlayer().StartRound();
            NAudio.Play("startgame");
            load.FinishLoading();
        }
Ejemplo n.º 17
0
        public IEnumerator StartScenario(string id, string map)
        {
            //load Map
            data.map.id = map;
            data.name   = LSys.tem.scenarios[id].Name();
            yield return(newMap.CreateMap());

            yield return(load.ShowSubMessage($"Loading players"));

            try
            {
                LClass.s.scenarioRuns[id].Run();
            }
            catch (Exception e)
            {
                ExceptionHelper.ShowException(e);
                throw e;
            }

            //add modis
            foreach (var option in L.b.gameOptions.GetAllByCategory("modi"))
            {
                if (!startConfig.ContainsKey(option.id))
                {
                    continue;
                }

                var val = Convert.ToInt32(startConfig[option.id]);
                if (val == 0)
                {
                    continue;
                }

                data.modi[option.id] = val + "%";
                Debug.Log(option.id + ":" + val + "%");
            }

            yield return(data.players.GameStart());

            yield return(data.players.GameBegin());

            yield return(data.players.NextPlayer());

            NAudio.Play("startgame");
            load.FinishLoading();
        }
Ejemplo n.º 18
0
        private void ShowDetail()
        {
            if (infoPanel.transform.childCount > 0)
            {
                foreach (Transform child in infoPanel.transform)
                {
                    Destroy(child.gameObject);
                }
                ;
            }

            PanelBuilder p = PanelBuilder.Create(infoPanel.transform);

            selectedElement.ShowDetail(p);
            p.CalcSize();
            NAudio.Play(selectedElement.audioSwitch);
        }
Ejemplo n.º 19
0
        private void ClickButton(SplitElement ele)
        {
            //same element?
            if (ele.disabled == null && ele == selectedElement && selectButton != null)
            {
                NAudio.Play(selectedElement.audioPerform);
                selectedElement.Perform();
                CloseWindow();
                return;
            }

            //show infos
            selectedElement = ele;

            //create panel
            ShowDetail();
            UpdateButton();
        }
Ejemplo n.º 20
0
        public virtual void Perform(MapElementInfo self, MapElementInfo nonSelf)
        {
            // calc damage
            int damage = CalcDamage(self, nonSelf);

            string a = $"{self.name} ({self.Player().name})";
            string d = $"{nonSelf.name} ({nonSelf.Player().name})";

            Debug.LogError("Damage:" + damage);

            // check it
            if (damage == 0)
            {
                OnMapUI.Get().unitUI.ShowPanelMessage(S.T("attackDamEqual", self.name, d));
                NAudio.Play("defend");
                //inform another player
                nonSelf.AddNoti($"Defended against {a}", self.baseData.Icon);
                return;
            }

            // counter fight
            if (damage < 0)
            {
                Perform(nonSelf, self);
                OnMapUI.Get().unitUI.ShowPanelMessage($"{d} fight back.");
                return;
            }

            // win
            ShowUnitAttack(self, nonSelf);
            nonSelf.AddHp(-damage);
            L.b.animations.Hp(-damage, nonSelf.Pos(), nonSelf);
            OnMapUI.Get().unitUI.ShowPanelMessage($"You won. {d} lose {damage} HP.");
            nonSelf.AddNoti($"{a} attacked you. {nonSelf.name} lose {damage} HP.", self.baseData.Icon);
            //int oX = defensor.getX();
            //int oY = defensor.getY();
            //UiHelper.textAnimation("-" + damage + " hp", oX, oY, true, Color.SALMON);

            //TODO add animation
            //defensor.getActor().addAction(Actions.sequence(Actions.color(Color.RED, 1), Actions.color(Color.WHITE, 1)));
            //getActor().addAction(Actions.parallel(Actions.sequence(Actions.moveTo(oX * 32, oY * 32, 1), Actions.moveTo(x * 32, y * 32, 1)),
            //    Actions.sequence(Actions.color(Color.BLACK, 1), Actions.color(Color.WHITE, 1))));
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Convert NAudio.Wave.WaveFormat to WavHeader
        /// </summary>
        public static ShazamO.WavHeader FormatToHeader(
            NAudio.Wave.WaveFormat WaveFormat, int FileSize)
        {
            ShazamO.WavHeader header = new ShazamO.WavHeader();
            header.AudioFormat = 1;
            header.BitsPerSample = (ushort)WaveFormat.BitsPerSample;
            header.BlockAlign = (ushort)WaveFormat.BlockAlign;
            header.ByteRate = (uint)WaveFormat.AverageBytesPerSecond;
            header.ChunkId = 0x46464952;
            header.ChunkSize = (uint)FileSize - 8;
            header.Format = 0x45564157;
            header.NumChannels = (ushort)WaveFormat.Channels;
            header.SampleRate = (uint)WaveFormat.SampleRate;
            header.Subchunk1Id = 0x20746d66;
            header.Subchunk1Size = 16;
            header.Subchunk2Id = 0x61746164;
            header.Subchunk2Size = (uint)(FileSize - Marshal.SizeOf(header.GetType()));

            return header;
        }
Ejemplo n.º 22
0
        public virtual void Click(NVector pos)
        {
            //known click?
            if (pos.Equals(LastClickPos))
            {
                ClickSecond();
                OnMapUI.Get().SetActiveAction(null, false);
                return;
            }

            //new Click?
            LastClickPos = pos;
            if (Points.Count(p => p.x == LastClickPos.x && p.y == LastClickPos.y) == 0)
            {
                NAudio.PlayCancel();
                ClickFirstCancel();
            }
            else
            {
                ClickFirst();
            }
        }
        private void sourceStream_DataAvailable(object sender, NAudio.Wave.WaveInEventArgs e)
        {
            byte[] waveData = e.Buffer;

            int globalMax = 0;
            int globalMin = 0;
            long p;
            for (p = 0; p < waveData.Length; p += bytesPerChannel)
            {
                int val = BitConverter.ToInt16(waveData, (int)p);
                if (val < globalMin) globalMin = val;
                if (val > globalMax) globalMax = val;
            }

            globalMin = -globalMin;
            if (globalMin > globalMax) globalMax = globalMin;

            int l = (int)((globalMax * 100) / (32768 >> level));
            if (l > 100) l = 100;
            if (l < 0) l = 0;
            audioLevel.Value = l;
        }
Ejemplo n.º 24
0
        public override void Click(NVector pos)
        {
            //known click?
            if (pos.Equals(LastClickPos))
            {
                ClickSecond();
                OnMapUI.Get().SetActiveAction(null, false);
                return;
            }

            //new Click?
            LastClickPos = pos;
            if (S.Unit().At(pos) != null)
            {
                NAudio.PlayCancel();
                ClickFirstCancel();
            }
            else
            {
                ClickFirst();
            }
        }
Ejemplo n.º 25
0
        public void AddInfoButton(Info info)
        {
            Button button = UIElements.CreateImageButton(SpriteHelper.Load(info.overviewIcon), infoButtons.transform, null);

            Action del = () =>
            {
                NAudio.PlayCancel();
                infoText.text = "";
                info.read     = true;
                Destroy(button.gameObject);

                //show res?
                if (infoButtons.GetComponentsInChildren <Transform>().Length <= 3)
                {
                    UpdatePanel();
                }
            };

            if (info.action == null)
            {
                button.onClick.AddListener(() =>
                {
                    del();
                    //todo add desc?
                    UIHelper.ShowOk("Notification", TextHelper.RichText(info.title, info.desc));
                });
            }
            else
            {
                button.onClick.AddListener(info.CallAction);
            }

            button.gameObject.AddComponent <ClickableObject>();
            button.GetComponent <ClickableObject>().right = del;

            UIHelper.HoverEnter(button, () => ShowPanelMessage(info.title), () => ShowPanelMessage(""));
        }
Ejemplo n.º 26
0
        private void ClickButton(SplitElement ele)
        {
            //disabled?
            if (ele.disabled != null)
            {
                //has a button?
                if (selectButton != null)
                {
                    UIHelper.UpdateButtonText(selectButton, ele.disabled);
                    selectButton.GetComponent <Button>().enabled = false;
                }

                selectedElement = ele;
                ShowDetail();
                return;
            }

            //same element?
            if (ele == selectedElement && selectButton != null)
            {
                NAudio.Play(selectedElement.audioPerform);
                selectedElement.Perform();
                return;
            }

            //show infos
            selectedElement = ele;
            if (selectButton != null)
            {
                selectButton.GetComponent <Button>().enabled = true;
                UIHelper.UpdateButtonText(selectButton, $"{selectButtonText} {ele.title}");
            }

            //create panel
            ShowDetail();
        }
Ejemplo n.º 27
0
        protected override void ClickFirst()
        {
            Debug.Log("Click first on " + LastClickPos);

            UnitInfo      unit    = (UnitInfo)mapElementInfo;
            string        moveTyp = unit.dataUnit.movement;
            var           path    = GameMgmt.Get().newMap.PathFinding(mapElementInfo.Pos().level);
            List <PPoint> way     = path.Path(player, moveTyp, mapElementInfo.Pos(), new NVector(LastClickPos.x, LastClickPos.y, mapElementInfo.Pos().level));

            if (way.Count == 0)
            {
                OnMapUI.Get().unitUI.ShowPanelMessage($"Can not move to this field. No path found.");
                NAudio.PlayBuzzer();
                return;
            }

            //show way
            Remove();
            int round = 0;
            int cost  = 0;

            Color(LastClickPos, 0);

            foreach (var p in way)
            {
                NVector pos = new NVector(p.x, p.y, LastClickPos.level);
                cost += path.CostNode(player, moveTyp, pos);
                if (cost > unit.data.ap + round * unit.data.apMax * round)
                {
                    round++;
                }
                Color(pos, round % 4);
            }

            OnMapUI.Get().unitUI.ShowPanelMessage($"You want to move to this field for {cost} AP? Click again!");
        }
Ejemplo n.º 28
0
        public void Create(string id, NVector pos)
        {
            NAnimation nAni = L.b.animations[id];

            //create animation
            var ani = AnimationObject.Create(pos);

            ani.sprites = nAni.Sprites();

            if (ani.sprites == null)
            {
                Debug.LogError(nAni.Icon + " is wrong formed");
                return;
            }
            Debug.Log(nAni.Icon + " found animation " + ani.sprites.Count);

            //play sound?
            if (!string.IsNullOrEmpty(nAni.sound))
            {
                NAudio.Play(nAni.sound);
            }

            ani.countMax = nAni.speed;
        }
 public static SerialPacketStream ReadAudioResource(string fileName, NAudio.Wave.WaveFormat format)
 {
     if (fileName.ToLower().EndsWith(".wav"))
     {
         var stream2 = App.GetResourceFileStream("MicActivate.wav");
         NAudio.Wave.WaveFileReader r = new NAudio.Wave.WaveFileReader(stream2);
         NAudio.Wave.ResamplerDmoStream s = new NAudio.Wave.ResamplerDmoStream(r, format);
         var length = (int)s.Length;
         byte[] resampled = new byte[length];
         s.Read(resampled, 0, length);
         var sps = new SerialPacketStream(resampled, format.SampleRate, fileName, 0, "self", false);
         return sps;
     }
     else if (fileName.ToLower().EndsWith(".pga"))
     {
         var stream = App.GetResourceFileStream("micTrigger.pga");
         var sps = SerialPacketStream.Read(stream);
         return sps;
     }
     else
     {
         throw new NotImplementedException();
     }
 }
        //send the Audio, in the eventarg's buffer , to the client.
        //TODO : add compression and play with the ACK when getting device output
        private void SendAudioData(object sender, NAudio.Wave.WaveInEventArgs e)
        {
            //the event args has a buffer with said data. its raw pcm, but over lan it'll do :D
            if (serverStarted > 0 && connection_init > 0 && data_send == 1)
            {
                //currently the ACK is disabled because with the PCM data being so big it causes lag on audio
                byte[] data = null;

                if (compressed)
                {
                    data = Compressor.Compress(e.Buffer);
                }
                else
                {
                    data = e.Buffer;
                }
                int ret = SendData(Protocol.SEND_DATA, data);
                //Debug.WriteLine("Compressed size: {0:F2}%",100 * ((double)data.Length / (double)e.Buffer.Length));
                data_send = 0;

                if (ret != data.Length)
                    closeServer();
            }

            return;
        }
Ejemplo n.º 31
0
 public void FFT(bool forward, int m, NAudio.Dsp.Complex[] data)
 {
 }
Ejemplo n.º 32
0
 private void RecordingStopped(object sender, NAudio.Wave.StoppedEventArgs e)
 {
     StatusManager.Status("WSAPI Recorder stopped.");
 }
Ejemplo n.º 33
0
 public OutputDeviceModel(NAudio.CoreAudioApi.MMDevice device)
     : base(device)
 {
 }
Ejemplo n.º 34
0
        /// <summary>
        /// Ensures valid AIFF header and then finds data offset.
        /// </summary>
        /// <param name="stream">The stream, positioned at the start of audio data</param>
        /// <param name="format">The format found</param>
        /// <param name="dataChunkPosition">The position of the data chunk</param>
        /// <param name="dataChunkLength">The length of the data chunk</param>
        /// <param name="chunks">Additional chunks found</param>
        public static void ReadAiffHeader(Stream stream, out NAudio.Wave.WaveFormat format, out long dataChunkPosition, out int dataChunkLength, List<AiffChunk> chunks)
        {
            dataChunkPosition = -1;
            format = null;
            BinaryReader br = new BinaryReader(stream);

            if (ReadChunkName(br) != "FORM")
            {
                throw new FormatException("Not an AIFF file - no FORM header.");
            }
            uint fileSize = ConvertLong(br.ReadBytes(4));
            if (ReadChunkName(br) != "AIFF")
            {
                throw new FormatException("Not an AIFF file - no AIFF header.");
            }

            dataChunkLength = 0;

            while (br.BaseStream.Position < br.BaseStream.Length)
            {
                AiffChunk nextChunk = ReadChunkHeader(br);
                if (nextChunk.chunkName == "COMM")
                {
                    short numChannels = ConvertShort(br.ReadBytes(2));
                    uint numSampleFrames = ConvertLong(br.ReadBytes(4));
                    short sampleSize = ConvertShort(br.ReadBytes(2));
                    double sampleRate = ConvertExtended(br.ReadBytes(10));

                    format = new NAudio.Wave.WaveFormat((int)sampleRate, (int)sampleSize, (int)numChannels);

                    br.ReadBytes((int)nextChunk.chunkLength - 18);
                }
                else if (nextChunk.chunkName == "SSND")
                {
                    uint offset = ConvertLong(br.ReadBytes(4));
                    uint blockSize = ConvertLong(br.ReadBytes(4));
                    dataChunkPosition = nextChunk.chunkStart + 16 + offset;
                    dataChunkLength = (int)nextChunk.chunkLength - 8;

                    br.ReadBytes((int)nextChunk.chunkLength - 8);
                }
                else
                {
                    if (chunks != null)
                    {
                        chunks.Add(nextChunk);
                    }
                    br.ReadBytes((int)nextChunk.chunkLength);
                }

                if (nextChunk.chunkName == "\0\0\0\0") break;
                //Console.WriteLine("Read chunk {0} with length {1}", nextChunk.chunkName, nextChunk.chunkLength);
            }

            if (format == null)
            {
                throw new FormatException("Invalid AIFF file - No COMM chunk found.");
            }
            if (dataChunkPosition == -1)
            {
                throw new FormatException("Invalid AIFF file - No SSND chunk found.");
            }
        }
Ejemplo n.º 35
0
 public void ShowPanelMessageError(string text)
 {
     OnMapUI.Get().bottomButtonText.color = Color.magenta;
     OnMapUI.Get().bottomButtonText.text = text;
     NAudio.PlayBuzzer();
 }
Ejemplo n.º 36
0
        private void SaveSample(object sender, NAudio.Wave.WaveInEventArgs e)
        {
            Sample sample = new Sample()
            {
                Id = CurrentTrack,
                Value = new Byte[e.BytesRecorded]
            };

            Array.Copy(e.Buffer, sample.Value, e.BytesRecorded);

            this.SilenceDetected = this.IsSilent(sample.Value);
            this.SoundDetected = !this.SilenceDetected;

            this.Buffer.AddSample(sample);
        }
Ejemplo n.º 37
0
 //Event args to check if Data is available
 private void wavSource_DataAvail(object sender, NAudio.Wave.WaveInEventArgs e)
 {
     if (wavFile != null)
     {
         wavFile.Write(e.Buffer, 0, e.BytesRecorded);
         wavFile.Flush();
     }
 }
Ejemplo n.º 38
0
            public SineWave(NAudio.Wave.WaveProvider32 provider)
            {
                // build a wave lookup tables for efficient calculations
                Table = new float[TABLE_SIZE];
                for (int i = 0; i < TABLE_SIZE; i++)
                {
                    Table[i] = (float)Math.Sin(i * Math.PI * 2.0 / (double)TABLE_SIZE);
                }

                this.provider = provider;

                // initialize variables to reasonable values
                frequency = 1000;
                phase_delta = (float)TABLE_SIZE * 1000 / (float)provider.WaveFormat.SampleRate;
                delta_percent = 1;
                SmoothTransition = true;
            }
Ejemplo n.º 39
0
        //Event args to stop recording events
        private void wavSource_RecordingStop(object sender, NAudio.Wave.StoppedEventArgs e)
        {
            if (wavSource != null)
            {
                wavSource.Dispose();
                wavSource = null;
            }

            if (wavFile != null)
            {
                wavFile.Dispose();
                wavFile = null;
            }
            //recBtn.Enabled = true;
        }
Ejemplo n.º 40
0
        private void sourceStream_DataAvailable(object sender, NAudio.Wave.WaveInEventArgs e)
        {
            if (recordToMp3.Checked)
            {
                if (mp3Writer == null || !mp3Writer.CanWrite)
                    return;

                mp3Writer.Write(e.Buffer, 0, e.BytesRecorded);
            }
            else
            {
                if (waveWriter == null)
                    return;
                waveWriter.Write(e.Buffer, 0, e.BytesRecorded);
                waveWriter.Flush();
            }
        }
Ejemplo n.º 41
0
        private void waveIn_DataAvailable(object sender, NAudio.Wave.WaveInEventArgs e)
        {
            // data available
            if (waveWriter == null) return;

            //waveWriter.Write(e.Buffer, 0, e.BytesRecorded);
            //waveWriter.Flush();
        }
Ejemplo n.º 42
0
 public override void Play(Transform source, bool worldSpace) => NAudio.PlaySound(sound, Pitch, source, worldSpace, volume, mixerGroup, distRange.min, distRange.max);
 public void OnFftCalculated(NAudio.Dsp.Complex[] result)
 {
     // nothing to do
 }
Ejemplo n.º 44
0
 public override void Play() => NAudio.PlaySound(sound, Pitch, volume, mixerGroup, distRange.min, distRange.max);
 public void OnFftCalculated(NAudio.Dsp.Complex[] result)
 {
     spectrumAnalyser.Update(result);
 }
        private void sourceStream_DataAvailable(object sender, NAudio.Wave.WaveInEventArgs e)
        {
            byte[] waveData = e.Buffer;

            int globalMax = 0;
            int globalMin = 0;
            long p;
            for (p = 0; p < waveData.Length; p += bytesPerChannel)
            {
                int val = BitConverter.ToInt16(waveData, (int)p);
                if (val < globalMin) globalMin = val;
                if (val > globalMax) globalMax = val;
            }

            globalMin = -globalMin;
            if (globalMin > globalMax) globalMax = globalMin;

            int l = (int)((globalMax * 100) / (32768 >> level));
            if (l > 100) l = 100;
            if (l < 0) l = 0;
            audioLevel.Value = l;

            if (isRecording)
            {
                if (!recordingFirstSkip)
                {
                    conductor.StartRecording(waveData.Length*4);
                    recordingFirstSkip = true;
                }

                recordingStream.Write(waveData, 0, waveData.Length);
            }
        }
Ejemplo n.º 47
0
        //druga himna
        void output_PlaybackStopped(object sender, NAudio.Wave.StoppedEventArgs e)
        {
            if(notClosed)
            {
                try
                {
                    DisposeWave();

                    byte[] gostPesma = AuxLib.LoadSoundFromGridFS(gost.Ime + "himna");
                    MemoryStream gostStream = new MemoryStream(gostPesma);
                    NAudio.Wave.WaveStream pcm = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(new NAudio.Wave.Mp3FileReader(gostStream));
                    stream = new NAudio.Wave.BlockAlignReductionStream(pcm);

                    output = new NAudio.Wave.DirectSoundOut();
                    output.Init(stream);

                    output.Play();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }
        }
Ejemplo n.º 48
0
 public OutputDeviceModel(int n, NAudio.Wave.WaveOutCapabilities capabilities)
     : base(n, capabilities)
 {
 }
Ejemplo n.º 49
0
 public override void Play(Vector3 worldPos) => NAudio.PlaySound(sound, Pitch, worldPos, volume, mixerGroup, distRange.min, distRange.max);
Ejemplo n.º 50
0
        private static void sourceStream_DataAvailable(object sender, NAudio.Wave.WaveInEventArgs e)
        {
            if (e.BytesRecorded < (882 * 2)) return;
            Buffer.BlockCopy(e.Buffer, 0, audioTemp, 0, 882 * 2);

            lock (audioLock)
            {
                for (int i = 0; i < 882; i++)
                    audioData[i] = audioTemp[i] / 32768f;
            }
        }
Ejemplo n.º 51
0
        /// <summary>
        /// Ensures valid AIFF header and then finds data offset.
        /// </summary>
        /// <param name="stream">The stream, positioned at the start of audio data</param>
        /// <param name="format">The format found</param>
        /// <param name="dataChunkPosition">The position of the data chunk</param>
        /// <param name="dataChunkLength">The length of the data chunk</param>
        /// <param name="chunks">Additional chunks found</param>
        public static void ReadAiffHeader(Stream stream, out NAudio.Wave.WaveFormat format, out long dataChunkPosition, out int dataChunkLength, List<AiffChunk> chunks)
        {
            dataChunkPosition = -1;
            format = null;
            BinaryReader br = new BinaryReader(stream);

            if (ReadChunkName(br) != "FORM")
            {
                throw new FormatException("Not an AIFF file - no FORM header.");
            }
            uint fileSize = ConvertInt(br.ReadBytes(4));
            string formType = ReadChunkName(br);
            if (formType != "AIFC" && formType != "AIFF")
            {
                throw new FormatException("Not an AIFF file - no AIFF/AIFC header.");
            }

            dataChunkLength = 0;

            while (br.BaseStream.Position < br.BaseStream.Length)
            {
                AiffChunk nextChunk = ReadChunkHeader(br);
                if (nextChunk.ChunkName == "COMM")
                {
                    short numChannels = ConvertShort(br.ReadBytes(2));
                    uint numSampleFrames = ConvertInt(br.ReadBytes(4));
                    short sampleSize = ConvertShort(br.ReadBytes(2));
                    double sampleRate = IEEE.ConvertFromIeeeExtended(br.ReadBytes(10));

                    format = new WaveFormat((int)sampleRate, (int)sampleSize, (int)numChannels);

                    if (nextChunk.ChunkLength > 18 && formType == "AIFC")
                    {
                        // In an AIFC file, the compression format is tacked on to the COMM chunk
                        string compress = new string(br.ReadChars(4)).ToLower();
                        if (compress != "none") throw new FormatException("Compressed AIFC is not supported.");
                        br.ReadBytes((int)nextChunk.ChunkLength - 22);
                    }
                    else br.ReadBytes((int)nextChunk.ChunkLength - 18);
                }
                else if (nextChunk.ChunkName == "SSND")
                {
                    uint offset = ConvertInt(br.ReadBytes(4));
                    uint blockSize = ConvertInt(br.ReadBytes(4));
                    dataChunkPosition = nextChunk.ChunkStart + 16 + offset;
                    dataChunkLength = (int)nextChunk.ChunkLength - 8;

                    br.ReadBytes((int)nextChunk.ChunkLength - 8);
                }
                else
                {
                    if (chunks != null)
                    {
                        chunks.Add(nextChunk);
                    }
                    br.ReadBytes((int)nextChunk.ChunkLength);
                }

                if (nextChunk.ChunkName == "\0\0\0\0") break;
            }

            if (format == null)
            {
                throw new FormatException("Invalid AIFF file - No COMM chunk found.");
            }
            if (dataChunkPosition == -1)
            {
                throw new FormatException("Invalid AIFF file - No SSND chunk found.");
            }
        }
Ejemplo n.º 52
0
        private void sourceStream_DataAvailable(object sender, NAudio.Wave.WaveInEventArgs e)
        {
            label10.Text = e.BytesRecorded.ToString();
            label11.Text = e.Buffer.Length.ToString();
            var buffer = e.Buffer;
            var buffer1 = new CircularBuffer<byte>(e.Buffer.Length-100,true);
            buffer1.Put(buffer);

            //buffer1.Clear();

            //MemoryStream memory = new MemoryStream(buffer);

            int i = 0;
            for (int index = 0; index < e.BytesRecorded; index += 2)
            {
                short sample = (short)((buffer[index + 1] << 8) | buffer[index]);
               // short sample = (short)(buffer[index]);
                //short sample=(short)(queue1.Enqueue((byte)index));
                float sample32 = sample / 32768f;
                t[i] = sample32;
                //memory.Dispose();

               // short truncated = (short)(Math.Pow(2,15)-1);
               // buffer[index]=(byte)(truncated & 0x00ff);
                //buffer[index+1]=(byte)((truncated & 0xff00)<<8);

                ++i;
            }
        }
Ejemplo n.º 53
0
 public void Run()
 {
     NAudio.Get().UpdateAudio();
 }
Ejemplo n.º 54
0
 void player_SampleReceived(object sender, NAudio.Wave.SampleEventArgs e)
 {
     soundEngine.AddSample(e.Left, e.Right);
 }
        private void sourceStream_DataAvailable(object sender, NAudio.Wave.WaveInEventArgs e)
        {
            if (waveWriter == null) return;

            waveWriter.WriteData(e.Buffer, 0, e.BytesRecorded);
            waveWriter.Flush();
        }
        private void sourceStream_DataAvailable(object sender, NAudio.Wave.WaveInEventArgs e)
        {
            if (calibrating) return;

            byte[] waveData = e.Buffer;

            int windowSize = 1000 * bytesPerSample;
            int globalMax = 0;
            int globalMin = 0;
            long n, p, q;
            for (n = p = 0; p < waveData.Length; p += bytesPerSample * 500, n++)
            {
                for (q = p; (q < waveData.Length) && (q < p + (bytesPerSample * 500)); q += bytesPerSample)
                {
                    int val = BitConverter.ToInt16(waveData, (int)q);
                    if (val < globalMin) globalMin = val;
                    if (val > globalMax) globalMax = val;
                }
            }

            globalMin = -globalMin;
            if (globalMin > globalMax) globalMax = globalMin;
            float factor = globalMax / ((float)(32768>>sensitivity));
            if (factor > 1.0f) factor = 1.0f;

            conductor.SetJaw(factor);
        }
Ejemplo n.º 57
-1
        private int GetNAudioMasterPeakValue(NAudio.CoreAudioApi.MMDevice device)
        {
            int result = 0;
            if (device == null)
                goto emptyReturn;

            try
            {
                result = (int)(Math.Round(device.AudioMeterInformation.MasterPeakValue * 100));
                return result;
            }
            catch (Exception)
            {
                goto emptyReturn;
            }

            emptyReturn:
            return 0;
        }
Ejemplo n.º 58
-1
 void wdt_OnDataAvailable(object sender, NAudio.Wave.WaveInEventArgs e)
 {
     //Console.Write('.');
     wdt_v.Write(e.Buffer, 0, e.BytesRecorded);
     wdt_writer.Write(e.Buffer, 0, e.BytesRecorded);
     double secondsRecorded = wdt_writer.Length / wdt_writer.WaveFormat.AverageBytesPerSecond;
     int nval = (int)(secondsRecorded * 25.5);
     if (nval > val) val = nval;
     if (secondsRecorded >= 10)
     {
         val = -100;
         wdt_waveIn.StopRecording();
     }
 }
Ejemplo n.º 59
-1
            public TriangleWave(NAudio.Wave.WaveProvider32 provider)
            {
                // build a wave lookup tables for efficient calculations
                Table = new float[TABLE_SIZE];
                for (int i = 0; i < TABLE_SIZE; i++)
                {
                    Table[i] = i < TABLE_SIZE / 2 ? 1.0f - 2.0f * i / (TABLE_SIZE / 2.0f) : -1.0f + 2.0f * (i - TABLE_SIZE / 2.0f) / (TABLE_SIZE / 2.0f);
                }

                this.provider = provider;

                // initialize variables to reasonable values
                frequency = 1000;
                phase_delta = (float)TABLE_SIZE * 1000 / (float)provider.WaveFormat.SampleRate;
                delta_percent = 1;
                SmoothTransition = false;
            }
Ejemplo n.º 60
-1
 public void fx_out_PlaybackStopped(object sender, NAudio.Wave.StoppedEventArgs e)
 {
     try
     {
         if (fx_out != null) fx_out.Dispose();
         if (fx_in != null) fx_in.Dispose();
     }
     catch { }
     done = true;
 }