コード例 #1
0
ファイル: Engine_Music.cs プロジェクト: unk1nd/US_AirForce
 public virtual void Dispose()
 {
     m_Audio.Stop();
     m_Audio.Dispose();
     m_Audio = null;
     m_Disposed = true;
 }
コード例 #2
0
        public void Search(List<Audio> source, Audio referenceItem, object parameters = null)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            if (referenceItem == null)
            {
                throw new ArgumentNullException("referenceItem");
            }

            Tempogram Descriptor = referenceItem.GetData<Tempogram>();

            if (Descriptor != null)
            {
                foreach (var Target in source)
                {
                    Tempogram Tempogram = Target.GetData<Tempogram>();
                    if (Tempogram == null)
                    {
                        Target.Tag = 10;
                        continue;
                    }

                    var d1 = Descriptor.LongTempogram.Distance(Tempogram.LongTempogram);
                    var d2 = Descriptor.ShortTempogram.Distance(Tempogram.ShortTempogram);
                    var d3 = Math.Abs(Descriptor.Intensity - Tempogram.Intensity);
                    Target.Tag = d1 + d2 * 0.0003f + d3 * 0.0002f;
                }
            }

            source.Sort((a1, a2) => a1.Tag.CompareTo(a2.Tag));
        }
 public Entity AddAudioPickupSource(Audio[] newClips, bool newRandomizePitch)
 {
     var component = _audioPickupSourceComponentPool.Count > 0 ? _audioPickupSourceComponentPool.Pop() : new AudioPickupSourceComponent();
     component.clips = newClips;
     component.randomizePitch = newRandomizePitch;
     return AddComponent(ComponentIds.AudioPickupSource, component);
 }
コード例 #4
0
        //select a song
        private void button1_Click(object sender, EventArgs e)
        {
            timer1.Stop();
            timer2.Stop();

            OpenFileDialog dlg = new OpenFileDialog();
            dlg.ShowDialog();
            song_path = dlg.FileName.ToString();
            textBox1.Text = song_path;
            try
            {

                song.Stop();
            }
            catch (Exception ex) { }

            try
            {
                song = new Audio(song_path);
                timer1.Interval = (int)(song.Duration * 10);
                progressBar1.Value = 0;
                //MessageBox.Show(timer1.Interval.ToString());
            }
            catch (Exception ex) { }
        }
コード例 #5
0
ファイル: SoundAlarm.cs プロジェクト: andrewjbennett/ZeoScope
        public SoundAlarm(string mp3FileName, string fadeInMinutes, string fadeOutMinutes, 
            string durationMinutes, string fromTime, string toTime, string snoozeTime, string alarmCue)
        {
            this.fadeInSeconds = (int)TimeSpan.Parse("00:" + fadeInMinutes).TotalSeconds; // 00 hours
            this.fadeOutSeconds = (int)TimeSpan.Parse("00:" + fadeOutMinutes).TotalSeconds; // 00 hours
            this.durationSeconds = (int)TimeSpan.Parse("00:" + durationMinutes).TotalSeconds; // 00 hours
            this.fromTime = fromTime;
            this.toTime = toTime;
            this.snoozeTime = snoozeTime;

            if (string.IsNullOrEmpty(this.fromTime) == true)
            {
                this.AlarmEnabled = true;
            }

            this.AlarmStarted = false;
            this.stopWatch = new Stopwatch();
            this.audio = new Audio(mp3FileName, false);
            this.audio.Volume = SoundAlarm.MinVolume;
            this.audio.Ending += new EventHandler(this.Audio_Ending);

            this.sleepStages = new List<ZeoSleepStage>();

            this.ParseAlarmCue(alarmCue);
        }
コード例 #6
0
 private static void AddAudioDocument(string[] attributes)
 {
     Dictionary<string, string> attr = getDictAttr(attributes);
     string documentName = returnNameCmdValue(attr);
     if (documentName != null)
     {
         Audio newDoc = new Audio(documentName);
         documents.Add(newDoc);
         Console.WriteLine("Document added: " + documentName);
         foreach (var key in attr.Keys)
         {
             switch (key)
             {
                 case "content":
                     newDoc.Content = attr[key];
                     break;
                 case "samplerate":
                     newDoc.SampleRateHz = attr[key];
                     break;
                 case "length":
                     newDoc.LengthInSeconds = attr[key];
                     break;
                 case "size":
                     newDoc.SizeInBytes = attr[key];
                     break;
             }
         }
     }
 }
コード例 #7
0
        // public static Time ttt = new Time();
        public MainWindow()
        {
            // ttt.reset();
            InitializeComponent();
            string filename = openFile("Select Audio (wav) file");
            string xmlfile = openFile("Select Score (xml) file");
            Time timer = new Time();
            file = new Audio(filename);
            timer.next("Load Audio");
            Thread check = new Thread(new ThreadStart(updateSlider));
            timer.next("slider thread");
            loadWave(filename);
            timer.next("setup");
            freqDomain();
            timer.next("freqDomain");
            sheetmusic = readXML(xmlfile);
            timer.next("sheetmusic");
            onsetDetection();
            timer.next("onsetDetection");
            loadImage();
            timer.next("loadImage");
            loadHistogram();
            timer.next("loadHistogram");
            playBack();
            timer.next("playBack");
            check.Start();

            button1.Click += zoomIN;
            button2.Click += zoomOUT;

            slider1.ValueChanged += updateHistogram;
            playback.PlaybackStopped += closeMusic;
            timer.end("Other stuff");
               // ttt.end("fft total");
        }
コード例 #8
0
ファイル: Music.cs プロジェクト: maestun/wonderboy
 public void Interrupt(Songs p_song)
 {
     this.audio.Stop();
     this.audio = new Audio(Utility.FindMediaFile(@"\Music\" + p_song.ToString() + ".mp3"));
     this.audio.Volume = -500;
     this.interupted = true;
 }
コード例 #9
0
        public AudioVisualizationSource(Audio.SampleAggregator aggregator)
        {
            this.aggregator = aggregator;

            MaximumCalculated += new EventHandler<MaxSampleEventArgs>(audioGraph_MaximumCalculated);
            FftCalculated += new EventHandler<FftEventArgs>(audioGraph_FftCalculated);
        }
コード例 #10
0
        public MainWindow()
        {
            InitializeComponent();
            string filename = @"C:\Users\Joe\Documents\fftmusic\music\WpfApplication1\Jupiter.wav";//openFile("Select Audio (wav) file");
            //string xmlfile = "C:\\Users\\Joe\\Documents\\fftmusic\\music\\WpfApplication1\\Jupiter.xml";// openFile("Select Score (xml) file");
            file = new Audio(filename);
            //Thread check = new Thread(new ThreadStart(updateSlider));
            loadWave(filename);
            int trials = 20;
            while (trials --> 0)
            {
                freqDomain();
            }
            //sheetmusic = readXML(xmlfile);
            //onsetDetection();
            //loadImage();
            //loadHistogram();
            //playBack();
            //check.Start();

            //button1.Click += zoomIN;
            //button2.Click += zoomOUT;

            //slider1.ValueChanged += updateHistogram;
            //playback.PlaybackStopped += closeMusic;
        }
コード例 #11
0
ファイル: Program.cs プロジェクト: lightofanima/Polys
    /** The entry point of the program. It controls the initialisation and defines the main game loop. */
    static void Main()
    {
        //Temporary solution to set the resource directory:
        System.IO.Directory.SetCurrentDirectory("..\\..\\res");

        //Initialise subsystems
        video = new Video();
        audio = new Audio();
        world = new World();
        input = new Input();

        ScriptManager.initialiseFromScript("configure.lua", video, audio, world, input);

        //Main loop
        while (world.running)
        {
            world.beforeInput();

            handleEvents();
            input.startFrame();

            world.afterInput();

            video.draw(world);
            audio.play(world);

            world.AfterLoop();
            input.endFrame();
        }

        world.Dispose();
        audio.Dispose();
        video.Dispose();
    }
コード例 #12
0
ファイル: SoundPlayer.cs プロジェクト: rajeper/ikarus-osd
        public static void Stop()
        {
            StopSoundThread();

            if (backMusic != null)
            {
                backMusic.Stop();
                backMusic.Dispose();
                backMusic = null;
            }

            if (soundHP != null)
            {
                soundHP.Stop();
                soundHP.Dispose();
                soundHP = null;
            }

            if (soundMP != null)
            {
                soundMP.Stop();
                soundMP.Dispose();
                soundMP = null;
            }

            queueLowPriority.Clear();
            queueMediumPriority.Clear();
            queueHighPriority.Clear();

            for (int i = 0; i < 3; i++)
                currentSounds[i] = "";
        }
    static void Main()
    {
        // Play a sound with the Audio class:
        Audio myAudio = new Audio();
        Console.WriteLine("Playing sound...");
        myAudio.Play(@"c:\WINDOWS\Media\chimes.wav");

        // Display time information with the Clock class:
        Clock myClock = new Clock();
        Console.Write("Current day of the week: ");
        Console.WriteLine(myClock.LocalTime.DayOfWeek);
        Console.Write("Current date and time: ");
        Console.WriteLine(myClock.LocalTime);

        // Display machine information with the Computer class:
        Computer myComputer = new Computer();
        Console.WriteLine("Computer name: " + myComputer.Name);

        if (myComputer.Network.IsAvailable)
        {
            Console.WriteLine("Computer is connected to network.");
        }
        else
        {
            Console.WriteLine("Computer is not connected to network.");
        }
    }
 public Entity AddAudioPickupSource(Audio[] newClips, bool newRandomizePitch)
 {
     var component = CreateComponent<AudioPickupSourceComponent>(ComponentIds.AudioPickupSource);
     component.clips = newClips;
     component.randomizePitch = newRandomizePitch;
     return AddComponent(ComponentIds.AudioPickupSource, component);
 }
コード例 #15
0
ファイル: ControleLecture.cs プロジェクト: joanny/Lecteur_mp3
        public string _ouvrir(typeFichier tf)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (tf == typeFichier.musique)
            {
                ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic);
                ofd.Filter = "mp3 files (*.mp3)|*.mp3";
                ofd.FilterIndex = 2;
                ofd.RestoreDirectory = true;

                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    if (ofd.OpenFile() != null)
                    {
                        try
                        {
                            Lecteur = new Audio(ofd.FileName, false);

                        }
                        catch (Exception esx)
                        {
                            MessageBox.Show("Fichier non reconnu." + esx.HResult);
                            return null;
                        }

                        return ofd.FileName;

                    }
                }
                return null;
            }
            else if (tf == typeFichier.image)
            {
                ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
                ofd.Filter = "JPG (*.jpg)|*.jpg";
                ofd.FilterIndex = 2;
                ofd.RestoreDirectory = true;

                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        if (ofd.OpenFile() != null)// On attribue le chemin du fichier à lire au
                        {

                            return ofd.FileName;

                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                        return null;
                    }
                }
                return null;

            }
            return null;
        }
コード例 #16
0
ファイル: DirectXPlayer.cs プロジェクト: zhuangyy/Motion
 public void Dispose()
 {
     if (mAudio != null)
     {
         mAudio.Dispose();
     }
     mAudio = null;
 }
コード例 #17
0
 public void toFinal(Audio qMusic, Audio qFinal, int qNumber)
 {
     if (qMusic.Playing == true && qNumber > 5) qMusic.Stop();
     qFinal.Play();
     ansLabel.ForeColor = Color.Black;
     ansPic.Image = Form3.getPictureRes(ansLetter + "_final");
     ansIfLocked = true;
 }
コード例 #18
0
ファイル: Audio.cs プロジェクト: bobjrsenior/GGJ_2016
 void OnLevelWasLoaded()
 {
     if(SceneManager.GetActiveScene().name.Equals("Demo Start"))
     {
         audioPlayer = null;
         Destroy(this.gameObject);
     }
 }
コード例 #19
0
ファイル: EventSink.cs プロジェクト: stevenzeiler/FeenPhone
 internal static void OnAudio(IFeenPhoneNetstate state, Guid userID, Audio.Codecs.CodecID Codec, byte[] data, int dataLen)
 {
     foreach (var feen in AllFeens)
         if (feen != state.Notifier && state.User != null)
             feen.OnAudio(userID, Codec, data, dataLen);
     if (ServerHost.LocalClient != null && ServerHost.LocalClient != state)
         ServerHost.LocalClient.Notifier.OnAudio(userID, Codec, data, dataLen);
 }
コード例 #20
0
 public MyObjectiveGetToLocations(StringBuilder Name, MyMissionID ID, StringBuilder Description, MyTexture2D Icon, MyMission ParentMission, MyMissionID[] RequiredMissions, List<MyMissionLocation> DummiesToVisit, Audio.Dialogues.MyDialogueEnum? successDialogId = null, Audio.Dialogues.MyDialogueEnum? startDialogId = null, bool displayObjectivesCount = true) :
     base(Name, ID, Description, Icon, ParentMission, RequiredMissions, null, null, successDialogId, startDialogId, displayObjectivesCount)
 {
     Debug.Assert(DummiesToVisit != null);
     Debug.Assert(DummiesToVisit.Count > 0);
     m_dummiesToVisit = DummiesToVisit;
     m_dummiesVisited = new List<MyMissionLocation>();
 }
コード例 #21
0
ファイル: Music.cs プロジェクト: Skinny1001/PlayUO
 public static void Dispose()
 {
     if (m_Audio != null)
     {
         m_Audio.Dispose();
     }
     m_Audio = null;
 }
 public Entity ReplaceAudioWalkSource(Audio[] newClips, bool newRandomizePitch)
 {
     var component = CreateComponent<AudioWalkSourceComponent>(ComponentIds.AudioWalkSource);
     component.clips = newClips;
     component.randomizePitch = newRandomizePitch;
     ReplaceComponent(ComponentIds.AudioWalkSource, component);
     return this;
 }
コード例 #23
0
ファイル: SoundA.cs プロジェクト: utau1116b/Hello-World
 private void Sound_Closed2()
 {
     // オーディオの破棄
     if (audio != null)
     {
         audio.Dispose();
         audio = null;
     }
 }
コード例 #24
0
ファイル: MapMaker.cs プロジェクト: roflwaffl/Phosphaze
        Wave wave; //wav file wrapper

        #endregion Fields

        #region Constructors

        //constructor takes in a Wave object which is used to initialize the fields
        public MapMaker(Wave w)
        {
            wave = w;
            wavAudio = new Audio(wave, 1000000);//1000000

            SBD = new StatBeatDetection(wave, 1000000);

            soundInformation = new SoundInfo[SBD.length() + 1];
        }
コード例 #25
0
        public SHA1HashDescriptor(Audio audio)
        {
            if (audio == null)
            {
                throw new ArgumentNullException("audio");
            }

            Hash = SHA1Hash.FromStream(audio.GetSourceStream());
        }
コード例 #26
0
ファイル: AudioDialog.cs プロジェクト: jmcadams/vplus
 public AudioDialog(EventSequence sequence, bool autoSize, int deviceIndex)
 {
     InitializeComponent();
     Icon = common.Resources.VixenPlus;
     _fmod = (deviceIndex > 0) ? fmod.GetInstance(deviceIndex) : fmod.GetInstance(-1);
     _timer = new Timer(10.0);
     _timer.Elapsed += TimerElapsed;
     _eventSequence = sequence;
     _keyStates = new bool[_eventSequence.FullChannelCount];
     _stopwatch = new Stopwatch();
     _newEventValues = new byte[_eventSequence.Rows,_eventSequence.Cols];
     listBoxChannels.Items.AddRange(_eventSequence.FullChannels.ToArray());
     _originalAudio = sequence.Audio;
     if (sequence.Audio != null) {
         if (LoadAudio(_eventSequence.Audio.FileName) == null) {
             sequence.Audio = null;
             buttonRemoveAudio.Enabled = false;
             ClearAudio();
         }
         else {
             buttonRemoveAudio.Enabled = true;
         }
     }
     else {
         buttonRemoveAudio.Enabled = false;
         ClearAudio();
     }
     checkBoxAutoSize.Checked = autoSize;
     if (!autoSize) {
         UpdateRecordableLength();
     }
     var items = (_eventSequence.FullChannels.ToArray());
     channel1ToolStripMenuItem.Items.AddRange(items);
     channel2ToolStripMenuItem.Items.AddRange(items);
     channel3ToolStripMenuItem.Items.AddRange(items);
     channel4ToolStripMenuItem.Items.AddRange(items);
     channel5ToolStripMenuItem.Items.AddRange(items);
     channel6ToolStripMenuItem.Items.AddRange(items);
     channel7ToolStripMenuItem.Items.AddRange(items);
     channel8ToolStripMenuItem.Items.AddRange(items);
     channel9ToolStripMenuItem.Items.AddRange(items);
     channel0ToolStripMenuItem.Items.AddRange(items);
     channel1ToolStripMenuItem.SelectedIndex = Math.Min(0, _eventSequence.FullChannelCount - 1);
     channel2ToolStripMenuItem.SelectedIndex = Math.Min(1, _eventSequence.FullChannelCount - 1);
     channel3ToolStripMenuItem.SelectedIndex = Math.Min(2, _eventSequence.FullChannelCount - 1);
     channel4ToolStripMenuItem.SelectedIndex = Math.Min(3, _eventSequence.FullChannelCount - 1);
     channel5ToolStripMenuItem.SelectedIndex = Math.Min(4, _eventSequence.FullChannelCount - 1);
     channel6ToolStripMenuItem.SelectedIndex = Math.Min(5, _eventSequence.FullChannelCount - 1);
     channel7ToolStripMenuItem.SelectedIndex = Math.Min(6, _eventSequence.FullChannelCount - 1);
     channel8ToolStripMenuItem.SelectedIndex = Math.Min(7, _eventSequence.FullChannelCount - 1);
     channel9ToolStripMenuItem.SelectedIndex = Math.Min(8, _eventSequence.FullChannelCount - 1);
     channel0ToolStripMenuItem.SelectedIndex = Math.Min(9, _eventSequence.FullChannelCount - 1);
     comboBoxAudioDevice.Items.Add(Resources.UseApplicationDefaultAudio);
     comboBoxAudioDevice.Items.AddRange(fmod.GetSoundDeviceList());
     comboBoxAudioDevice.SelectedIndex = _eventSequence.AudioDeviceIndex + 1;
 }
コード例 #27
0
ファイル: SharpDXHelper.cs プロジェクト: temik911/audio
        /// <summary>
        /// 
        /// </summary>
        /// <param name="curve"></param>
        /// <returns></returns>
        public static SharpDX.X3DAudio.CurvePoint[] Convert( Audio.CurvePoint[] curve )
        {
            if (curve==null) {
                return null;
            }

            return curve
                .Select( c => new SharpDX.X3DAudio.CurvePoint{ Distance = c.Distance, DspSetting = c.DspSetting } )
                .ToArray();
        }
コード例 #28
0
ファイル: DirectXPlayer.cs プロジェクト: zhuangyy/Motion
 public void AlarmStart()
 {
     if (mAudio != null)
     {
         mAudio.Dispose();
     }
     mAudio = new Audio(mFileName);
     mAudio.Ending += new EventHandler(mAudio_Ending);
     mAudio.Play();
 }
コード例 #29
0
ファイル: Music.cs プロジェクト: Skinny1001/PlayUO
 public static void Stop()
 {
     if (m_Audio != null)
     {
         m_Audio.Stop();
         m_Audio.Dispose();
         m_Audio = null;
         m_FileName = null;
     }
 }
コード例 #30
0
ファイル: AudioRepository.cs プロジェクト: iowen/ysl
 public AudioModel convertAudioToModel(Audio item)
 {
     return new AudioModel
     {
         AudioId = item.AudioId,
         Description = item.Description,
         Location = item.Location,
         Title = item.Title
     };
 }
コード例 #31
0
        public override IEnumerable <Issue> GetIssues(BeatmapSet beatmapSet)
        {
            foreach (string hsFile in beatmapSet.hitSoundFiles)
            {
                // Only hit sounds on active hit objects need to be delay-free.
                bool isActive = IsActive(beatmapSet, hsFile);
                if (!isActive)
                {
                    continue;
                }

                string hsPath = Path.Combine(beatmapSet.songPath, hsFile);

                List <float[]> peaks     = null;
                Exception      exception = null;
                try
                { peaks = Audio.GetPeaks(hsPath); }
                catch (Exception ex)
                { exception = ex; }

                if (exception == null)
                {
                    // Ignore muted files since they don't have anything to be delayed.
                    if (peaks?.Count > 0 && peaks.Sum(peak => peak.Sum()) > 0)
                    {
                        double maxStrength = peaks.Select(value => Math.Abs(value.Sum())).Max();

                        int    delay     = 0;
                        int    pureDelay = 0;
                        double strength  = 0;
                        while (delay + pureDelay < peaks.Count)
                        {
                            strength += Math.Abs(peaks[delay].Sum());

                            if (strength >= maxStrength / 2)
                            {
                                break;
                            }

                            strength *= 0.95;

                            // The delay added by MP3 encoding still has very slight volume where it's basically silent.
                            if (strength < 0.001)
                            {
                                strength = 0;
                                ++pureDelay;
                                ++delay;
                            }
                            else
                            {
                                ++delay;
                            }
                        }

                        if (pureDelay >= 5)
                        {
                            yield return(new Issue(GetTemplate("Pure Delay"), null,
                                                   hsFile, $"{pureDelay:0.##}"));
                        }

                        else if (delay + pureDelay >= 5)
                        {
                            yield return(new Issue(GetTemplate("Delay"), null,
                                                   hsFile, $"{pureDelay:0.##}", $"{delay:0.##}"));
                        }

                        else if (delay + pureDelay >= 1)
                        {
                            yield return(new Issue(GetTemplate("Minor Delay"), null,
                                                   hsFile, $"{pureDelay:0.##}", $"{delay:0.##}"));
                        }
                    }
                }
                else
                {
                    yield return(new Issue(GetTemplate("Unable to check"), null,
                                           hsFile, Common.AsExceptionDiv(exception)));
                }
            }
        }
コード例 #32
0
        public override void Update()
        {
            // Note: You may instinctually call base.Update();
            // DON'T! The original method is orig_Update

            if (Everest.Flags.IsDisabled)
            {
                orig_Update();
                return;
            }

            KeyboardState keysPrev = _keys;
            KeyboardState keys     = Keyboard.GetState();

            _keys = keys;

            if (Focused && !disableInput && display)
            {
                if (Input.Pause.Pressed || Input.ESC.Pressed)
                {
                    Overworld.Maddy.Hide(true);
                    Audio.Play(SFX.ui_main_button_select);
                    Audio.Play(SFX.ui_main_whoosh_large_in);
                    OuiMapList list = Overworld.Goto <OuiMapList>();
                    list.OuiIcons = icons;
                    return;
                }
                else if (Input.QuickRestart.Pressed)
                {
                    Overworld.Maddy.Hide(true);
                    Audio.Play(SFX.ui_main_button_select);
                    Audio.Play(SFX.ui_main_whoosh_large_in);
                    OuiMapSearch list = Overworld.Goto <OuiMapSearch>();
                    list.OuiIcons = icons;
                    return;
                }
            }

            // note: Engine.DeltaTime is removed from inputDelay before being compared to zero in the orig method.
            if (Focused && display && !disableInput && inputDelay <= Engine.DeltaTime)
            {
                if (Input.MenuUp.Pressed)
                {
                    Audio.Play(SFX.ui_world_chapter_pane_contract);
                    Audio.Play(SFX.ui_world_icon_roll_left);
                    Overworld.Goto <OuiHelper_ChapterSelect_LevelSet>().Direction = -1;
                    return;
                }
                if (Input.MenuDown.Pressed)
                {
                    Audio.Play(SFX.ui_world_chapter_pane_expand);
                    Audio.Play(SFX.ui_world_icon_roll_right);
                    Overworld.Goto <OuiHelper_ChapterSelect_LevelSet>().Direction = +1;
                    return;
                }

                if (keys[Keys.F5] == KeyState.Down && keysPrev[Keys.F5] == KeyState.Up)
                {
                    Audio.Play(SFX.ui_postgame_unlock_newchapter);
                    Audio.Play(SFX.ui_world_whoosh_1000ms_forward);
                    Overworld.Goto <OuiHelper_ChapterSelect_Reload>();
                    return;
                }

                // We don't want to copy the entire Update method, but still prevent the option from going out of bounds.
                GetMinMaxArea(out int areaOffs, out int areaMax);
                if (area < areaOffs)
                {
                    area = areaOffs;
                }
                else
                {
                    if (area > areaMax)
                    {
                        area = areaMax;
                    }
                    while (area > 0 && icons[area].GetIsHidden())
                    {
                        area--;
                    }
                }

                if (Input.MenuLeft.Pressed && (area - 1 < 0 || icons[area - 1].GetIsHidden()))
                {
                    return;
                }

                if (Input.MenuRight.Pressed && (area + 1 >= icons.Count || icons[area + 1].GetIsHidden()))
                {
                    return;
                }
            }

            orig_Update();

            if (Focused && display)
            {
                updateScarf();
            }

            maplistEase  = Calc.Approach(maplistEase, (display && !disableInput && Focused) ? 1f : 0f, Engine.DeltaTime * 4f);
            searchEase   = Calc.Approach(searchEase, (display && !disableInput && Focused) ? 1f : 0f, Engine.DeltaTime * 4f);
            levelsetEase = Calc.Approach(levelsetEase, (display && !disableInput && Focused) ? 1f : 0f, Engine.DeltaTime * 4f);
        }
コード例 #33
0
ファイル: EventsOn00.cs プロジェクト: domnescu/BigBrother_Bot
        /// <summary>
        /// Действия в 00 Минут каждого часа
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task Execute(IJobExecutionContext context)
        {
            Database database = new Database();

            if (DateTime.Now.Hour == 00)
            {
                database.CleanTable("Votes");
                database.SetWorkingVariable("VoteAcces", "open");
                Dictionary <string, string> warnings = database.GetDictionaryString("WarningList");
                foreach (var warning in warnings)
                {
                    if (warning.Value != "опер")
                    {
                        string tempString = database.RandomResponse("RandomNewInfo");
                        tempString = tempString.Replace("{warning}", warning.Value);
                        database.InfoUpdate(warning.Value, tempString);
                    }
                }
            }
            else if ((DateTime.Now.Day == 31 && DateTime.Now.Month == 12) || (DateTime.Now.Day == 01 && DateTime.Now.Month == 01))
            {
                VkApi    client = new VkApi();
                Database db     = new Database();
                client.Authorize(new ApiAuthParams()
                {
                    AccessToken = db.GetWorkingVariable("BigBroKey")
                });
                MessagesSendParams @params = new MessagesSendParams();
                Audio Track = new Audio();
                Track.OwnerId = -187905748;
                if (DateTime.Now.Day == 31 && DateTime.Now.Hour == 14)
                {
                    @params.Message = "Так)) ещё немного и у кого-то начнётся веселье))\nНастоятельно рекомендую слушать песни которые я буду отправлять))" +
                                      "99% что поднимут настроение, если не поднимут, то вы ещё недостаточно выпили!!";
                }
                else if (DateTime.Now.Day == 31 && DateTime.Now.Hour == 15)
                {
                    @params.Message = "С Новым годом! Пусть к чёрту катятся все проблемы! Пусть трезвый Дед Мороз подарит опьяняющее счастье трезвой реальности!" +
                                      " Желаю крутых подъёмов в новом году, максимальных доходов, желаемых результатов в делах и невероятно страстных чувств в отношениях!";
                    Track.Id = 456239033;
                }
                else if (DateTime.Now.Day == 31 && DateTime.Now.Hour == 16)
                {
                    @params.Message = "Новый год стучится в двери, а это значит, что пора пинком под зад отправить все проблемы, запастись охапками продуктов и" +
                                      " с широкою, довольною улыбкой набираться позитива. Улыбайтесь же и веселитесь, гоните в шею все дурные мысли! Как шампанское, бурлите " +
                                      "от радости и мечтайте о великих перспективах!";
                    Track.Id = 456239018;
                }
                else if (DateTime.Now.Day == 31 && DateTime.Now.Hour == 17)
                {
                    @params.Message = "С Новым годом! Желаю быть чудом весь чудесный год, желаю снегопада денег и вьюги удачи, вихря счастья и бурана любви. " +
                                      "Пусть этот год будет суперским и мега-крутым, а в нём пусть будет и драйв, и кайф, и роскошь!";
                    Track.Id = 456239020;
                }
                else if (DateTime.Now.Day == 31 && DateTime.Now.Hour == 18)
                {
                    @params.Message = "С Новым годом! Желаю выбросить и носки с дырками, и мысли с глупостями, и сомнения по любому поводу. Надеюсь, твоё " +
                                      "поведение было прилежным, и Дед Мороз подарит тебе что-то хорошее. Желаю круто встретить новый год и провести его под громким девизом " +
                                      "постоянного счастья!";
                    Track.Id = 456239022;
                }
                else if (DateTime.Now.Day == 31 && DateTime.Now.Hour == 19)
                {
                    @params.Message = "Пусть Дед Мороз не забудет исполнить все пожелания, президент в полночь пообещает что-то оригинальное, а соседи наберут " +
                                      "самых красочных петард для праздничного салюта. Отдайте уходящему году мешок со всеми долгами, неприятностями и невзгодами, обратный " +
                                      "адрес не указывайте. С Новым годом!";
                    Track.Id = 456239037;
                }
                else if (DateTime.Now.Day == 31 && DateTime.Now.Hour == 20)
                {
                    @params.Message = "Поздравляю с Новым годом! Пусть всегда удаётся смотреть трезво на жизнь, но в то же время быть в опьянении от счастья. " +
                                      "Желаю, чтобы шампусик смыл прошлые обиды и печали, чтобы в новом году было столько удачи и веселья, сколько горошинок в самом большом " +
                                      "тазу оливье!";
                    Track.Id = 456239034;
                }
                else if (DateTime.Now.Day == 31 && DateTime.Now.Hour == 21)
                {
                    @params.Message = "С Новым годом! Желаю встретить его без похмелья, но с весёлыми приключениями на пятую точку! Пусть всё будет, как в доброй" +
                                      " сказке, как в старом хорошем фильме. Желаю, чтобы заливная рыба была совсем не гадостью, чтобы тебя никто не поливал из чайника, чтобы " +
                                      "не потянуло ни в баню, ни в Ленинград. Пусть новый год сорит деньгами и бьёт битой всех обидчиков!";
                    Track.Id = 456239035;
                }
                else if (DateTime.Now.Day == 31 && DateTime.Now.Hour == 22)
                {
                    @params.Message = "Поздравляю с Новым годом и от души желаю если хреновины, то только к холодцу, если падения, то только в объятия любимого " +
                                      "человека, если страха, то только у врагов, если мусора, то только в виде бутылок от дорогого алкоголя и контейнеров от обалденной икры.";
                    Track.Id = 456239036;
                }
                else if (DateTime.Now.Day == 31 && DateTime.Now.Hour == 23)
                {
                    @params.Message = "Пусть на утро января не болит голова от выпитого, чтобы желания сбываться начали уже с этого дня. Желаю под елкой найти мешок" +
                                      " с деньгами, чтобы хватало на многие года вперед. С Новым годом!";
                    Track.Id = 456239032;
                }
                else if (DateTime.Now.Day == 01 && DateTime.Now.Hour == 00)
                {
                    @params.Message = "Желаю в Новом году всем крепкой печени и внутреннего навигатора, чтобы точно знать как вы пришли туда, где проснулись.";
                    Track.Id        = 456239028;
                }
                else if (DateTime.Now.Day == 01 && DateTime.Now.Hour == 01)
                {
                    @params.Message = "С Новым годом. Желаю «не ударить» в Оливье лицом, желаю шампанское и прочие горючие хорошенько закусывать холодцом, желаю" +
                                      " в Новом году быть огурцом, желаю утро нового календаря встретить радостно и без похмелья. А ещё желаю здоровья, ума и денег!";
                    Track.Id = 456239023;
                }

                List <long> Chats = db.GetListLong("MainMakara");
                foreach (var chat in Chats)
                {
                    if (Track.Id != null)
                    {
                        @params.Attachments = new[] { Track }
                    }
                    ;
                    @params.RandomId = new Random().Next();
                    @params.PeerId   = chat;
                    client.Messages.Send(@params);
                }
            }
            database.CleanTable("ComandsFromUser");

            return(null);
        }
    }
コード例 #34
0
        public void ChangeAudio(Audio newGrooveAudio, int grooveBarPosition)
        {
            WaveStream wavestream = AudioToWaveStream(newGrooveAudio);

            queuedWaveStream.UpdateStreamAtPosition(wavestream, grooveBarPosition);
        }
コード例 #35
0
 public void PlayCountdownBeep()
 {
     Audio.PlaySoundFrontend("5_SEC_WARNING", "HUD_MINI_GAME_SOUNDSET");
 }
コード例 #36
0
        /// <summary>
        /// The create audio.
        /// </summary>
        /// <param name="job">
        /// The job.
        /// </param>
        /// <returns>
        /// The <see cref="Audio"/>.
        /// </returns>
        private static Audio CreateAudio(EncodeTask job)
        {
            Audio audio = new Audio();

            List <uint> copyMaskList = new List <uint>();

            if (job.AllowedPassthruOptions.AudioAllowAACPass)
            {
                copyMaskList.Add(NativeConstants.HB_ACODEC_AAC_PASS);
            }
            if (job.AllowedPassthruOptions.AudioAllowAC3Pass)
            {
                copyMaskList.Add(NativeConstants.HB_ACODEC_AC3_PASS);
            }
            if (job.AllowedPassthruOptions.AudioAllowDTSHDPass)
            {
                copyMaskList.Add(NativeConstants.HB_ACODEC_DCA_HD_PASS);
            }
            if (job.AllowedPassthruOptions.AudioAllowDTSPass)
            {
                copyMaskList.Add(NativeConstants.HB_ACODEC_DCA_PASS);
            }
            if (job.AllowedPassthruOptions.AudioAllowEAC3Pass)
            {
                copyMaskList.Add(NativeConstants.HB_ACODEC_EAC3_PASS);
            }
            if (job.AllowedPassthruOptions.AudioAllowFlacPass)
            {
                copyMaskList.Add(NativeConstants.HB_ACODEC_FLAC_PASS);
            }
            if (job.AllowedPassthruOptions.AudioAllowMP3Pass)
            {
                copyMaskList.Add(NativeConstants.HB_ACODEC_MP3_PASS);
            }
            if (job.AllowedPassthruOptions.AudioAllowTrueHDPass)
            {
                copyMaskList.Add(NativeConstants.HB_ACODEC_TRUEHD_PASS);
            }
            audio.CopyMask = copyMaskList.ToArray();

            HBAudioEncoder audioEncoder = HandBrakeEncoderHelpers.GetAudioEncoder(EnumHelper <AudioEncoder> .GetShortName(job.AllowedPassthruOptions.AudioEncoderFallback));

            audio.FallbackEncoder = audioEncoder.Id;

            audio.AudioList = new List <HandBrake.ApplicationServices.Interop.Json.Encode.AudioTrack>();
            foreach (AudioTrack item in job.AudioTracks)
            {
                HBAudioEncoder encoder = HandBrakeEncoderHelpers.GetAudioEncoder(EnumHelper <AudioEncoder> .GetShortName(item.Encoder));
                Validate.NotNull(encoder, "Unrecognized audio encoder:" + item.Encoder);

                HBMixdown mixdown = HandBrakeEncoderHelpers.GetMixdown(item.MixDown);

                HBRate sampleRate = HandBrakeEncoderHelpers.AudioSampleRates.FirstOrDefault(s => s.Name == item.SampleRate.ToString(CultureInfo.InvariantCulture));

                HandBrake.ApplicationServices.Interop.Json.Encode.AudioTrack audioTrack = new HandBrake.ApplicationServices.Interop.Json.Encode.AudioTrack
                {
                    Track             = (item.Track.HasValue ? item.Track.Value : 0) - 1,
                    DRC               = item.DRC,
                    Encoder           = encoder.Id,
                    Gain              = item.Gain,
                    Mixdown           = mixdown != null ? mixdown.Id : -1,
                    NormalizeMixLevel = false,
                    Samplerate        = sampleRate != null ? sampleRate.Rate : 0,
                    Name              = !string.IsNullOrEmpty(item.TrackName) ? item.TrackName : null,
                };

                if (!item.IsPassthru)
                {
                    if (item.EncoderRateType == AudioEncoderRateType.Quality)
                    {
                        audioTrack.Quality = item.Quality;
                    }

                    if (item.EncoderRateType == AudioEncoderRateType.Bitrate)
                    {
                        audioTrack.Bitrate = item.Bitrate;
                    }
                }

                audio.AudioList.Add(audioTrack);
            }

            return(audio);
        }
コード例 #37
0
    private static IEnumerator SelectOnPage(FloatingHoldable holdable, int index = 0, IList <string> search = null)
    {
        if (TwitchPlaysService.Instance.CurrentState != KMGameInfo.State.Setup)
        {
            yield break;
        }

        if (index > 0 || (search != null && search.Count > 0))
        {
            if ((_currentSelectables == null) || (index > _currentSelectables.Length))
            {
                yield break;
            }

            int oldSelectableIndex = _currentSelectableIndex;

            int        i             = 0;
            Selectable newSelectable = null;
            for (_currentSelectableIndex = 0; _currentSelectableIndex < _currentSelectables.Length; ++_currentSelectableIndex)
            {
                if (_currentSelectables[_currentSelectableIndex] == null)
                {
                    continue;
                }

                // Index mode
                if (index > 0)
                {
                    if (++i == index)
                    {
                        newSelectable = _currentSelectables[_currentSelectableIndex];
                        break;
                    }
                }
                // Search mode
                else
                {
                    var mission = _currentSelectables[_currentSelectableIndex].GetComponent <MissionTableOfContentsMissionEntry>();

                    if (mission == null)
                    {
                        continue;
                    }

                    string missionName = mission.EntryText.text.ToLowerInvariant();

                    // Trigger the mission if EITHER
                    // • the first search term matches the mission ID (e.g., "2.1"); OR
                    // • all search terms are found in the mission name
                    if (mission.SubsectionText.text.Equals(search?[0], StringComparison.InvariantCultureIgnoreCase) || search.All(s => missionName.ContainsIgnoreCase(s)))
                    {
                        newSelectable = _currentSelectables[_currentSelectableIndex];
                        break;
                    }
                }
            }

            if (newSelectable == null)
            {
                _currentSelectableIndex = oldSelectableIndex;
                yield break;
            }

            _currentSelectable.HandleDeselect();
            _currentSelectable = newSelectable;
        }

        if (_currentSelectable == null)
        {
            yield break;
        }

        _currentSelectable.HandleSelect(true);
        KTInputManager.Instance.SelectableManager.Select(_currentSelectable, true);

        // Prevent users from trying to start the tutorial missions, assuming they actually selected a mission.
        var selectedMission = _currentSelectable.GetComponent <MissionTableOfContentsMissionEntry>();

        if (selectedMission != null && MissionManager.Instance.GetMission(selectedMission.MissionID).IsTutorial)
        {
            Audio.PlaySound(KMSoundOverride.SoundEffect.Strike, _currentSelectable.transform);
            IRCConnection.SendMessage("The tutorial missions are currently unsupported and cannot be selected.");
            yield break;
        }

        KTInputManager.Instance.SelectableManager.HandleInteract();
        _currentSelectable.OnInteractEnded();

        yield return(null);

        InitializePage(holdable);
    }
コード例 #38
0
        public void CreatePauseMenuButtons(Level level, TextMenu menu, bool minimal)
        {
            if (!Settings.ShowModOptionsInGame)
            {
                return;
            }

            List <TextMenu.Item> items = menu.GetItems();
            int index;

            // Find the options button and place our button below it.
            string cleanedOptions = Dialog.Clean("menu_pause_options");

            index = items.FindIndex(_ => {
                TextMenu.Button other = (_ as TextMenu.Button);
                if (other == null)
                {
                    return(false);
                }
                return(other.Label == cleanedOptions);
            });
            if (index != -1)
            {
                index++;
            }
            // Otherwise, place it below the last button.
            else
            {
                index = items.Count;
            }

            TextMenu.Item itemModOptions = null;
            menu.Insert(index, itemModOptions = new TextMenu.Button(Dialog.Clean("menu_pause_modoptions")).Pressed(() => {
                int returnIndex = menu.IndexOf(itemModOptions);
                menu.RemoveSelf();

                level.PauseMainMenuOpen = false;
                level.Paused            = true;

                TextMenu options = OuiModOptions.CreateMenu(true, LevelExt.PauseSnapshot);

                options.OnESC = options.OnCancel = () => {
                    Audio.Play(SFX.ui_main_button_back);
                    options.CloseAndRun(Everest.SaveSettings(), () => {
                        level.Pause(returnIndex, minimal, false);

                        // adjust the Mod Options menu position, in case it moved (pause menu entries added/removed after changing mod options).
                        TextMenu textMenu = level.Entities.GetToAdd().FirstOrDefault((Entity e) => e is TextMenu) as TextMenu;
                        TextMenu.Button modOptionsButton = textMenu?.GetItems().OfType <TextMenu.Button>()
                                                           .FirstOrDefault(button => button.Label == Dialog.Clean("menu_pause_modoptions"));
                        if (modOptionsButton != null)
                        {
                            textMenu.Selection = textMenu.IndexOf(modOptionsButton);
                        }
                    });
                };

                options.OnPause = () => {
                    Audio.Play(SFX.ui_main_button_back);
                    options.CloseAndRun(Everest.SaveSettings(), () => {
                        level.Paused       = false;
                        Engine.FreezeTimer = 0.15f;
                    });
                };

                level.Add(options);
            }));
        }
コード例 #39
0
ファイル: Program.cs プロジェクト: FIEforever/SysDVR
        static void StartUsbStreaming(IMutliStreamManager Streams, string[] args)
        {
            bool     PrintStats  = false;
            LogLevel UsbLogLevel = LogLevel.Error;

            bool HasArg(string arg) => Array.IndexOf(args, arg) != -1;

            if (HasArg("--desync-fix"))
            {
                Console.WriteLine("Warning: the --desync-fix fix option has been deprecated and will be ignored");
            }

            PrintStats = HasArg("--print-stats");
            if (HasArg("--usb-warn"))
            {
                UsbLogLevel = LogLevel.Info;
            }
            if (HasArg("--usb-debug"))
            {
                UsbLogLevel = LogLevel.Debug;
            }

            if (Streams == null || !Streams.HasAStream)
            {
                Console.WriteLine("Specify at least a video or audio target");
                return;
            }

            var stream = GetDevice(UsbLogLevel);

            if (stream == null)
            {
                Console.WriteLine("Device not found, did you configure the drivers properly ?");
                return;
            }

            CancellationTokenSource StopThreads = new CancellationTokenSource();

            VideoStreamThread Video = null;

            if (Streams.Video != null)
            {
                Video = new VideoStreamThread(StopThreads.Token, Streams.Video, stream.OpenStreamDefault(), PrintStats);
            }

            AudioStreamThread Audio = null;

            if (Streams.Audio != null)
            {
                Audio = new AudioStreamThread(StopThreads.Token, Streams.Audio, stream.OpenStreamAlt(), PrintStats);
            }

            Video?.Start();
            Audio?.Start();

            //If streaming via RTSP use managed streaming, this part should be reworked in the future, maybe using "managed streams" only
            if (Streams is RTSP.SysDvrRTSPServer || Streams is TCPBridgeManager)
            {
                StartManagedStreaming(Streams, null);
            }
            else
            {
                Streams.Begin();
                Console.WriteLine("If the stream lags press Q to force a resync");
                ConsoleKey c;
                while ((c = Console.ReadKey().Key) != ConsoleKey.Enter)
                {
                    if (c == ConsoleKey.Q)
                    {
                        Console.WriteLine("Pausing streams for 3 seconds to flush buffer data");
                        Video?.Pause();
                        Audio?.Pause();
                        Thread.Sleep(3000);
                        Video?.Resume();
                        Audio?.Resume();
                    }
                }

                Console.WriteLine("Terminating threads...");
                Streams.Stop();
                Streams.Dispose();
            }

            StopThreads.Cancel();
            Video?.Join();
            Audio?.Join();

            Video?.Dispose();
            Audio?.Dispose();

            LibUsbCtx.Dispose();
        }
コード例 #40
0
ファイル: frmPlayList.cs プロジェクト: hiroshica/MDPlayer
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (!playing)
            {
                return;
            }
            if (setting == null)
            {
                return;
            }

            string fn    = "";
            string arcFn = "";

            Audio.getPlayingFileName(out fn, out arcFn);

            if (fn == ofn && arcFn == oafn)
            {
                return;
            }
            ofn  = fn;
            oafn = arcFn;

            exts[0] = setting.other.TextExt.Split(';');
            exts[1] = setting.other.MMLExt.Split(';');
            exts[2] = setting.other.ImageExt.Split(';');

            string bfn = Path.Combine(Path.GetDirectoryName(fn), Path.GetFileNameWithoutExtension(fn));

            text = "";
            foreach (string ext in exts[0])
            {
                if (File.Exists(bfn + "." + ext))
                {
                    text = bfn + "." + ext;
                    break;
                }
            }
            mml = "";
            foreach (string ext in exts[1])
            {
                if (File.Exists(bfn + "." + ext))
                {
                    mml = bfn + "." + ext;
                    break;
                }
            }
            img = "";
            foreach (string ext in exts[2])
            {
                if (File.Exists(bfn + "." + ext))
                {
                    img = bfn + "." + ext;
                    break;
                }
            }

            tsbTextExt.Enabled = (text != "");
            tsbMMLExt.Enabled  = (mml != "");
            tsbImgExt.Enabled  = (img != "");
        }
コード例 #41
0
 // Start is called before the first frame update
 void Start()
 {
     point   = 0;
     rank    = 1;
     myaudio = GetComponent <Audio>();
 }
コード例 #42
0
 public static void Download(this IAudioCategory audioCategory, Audio audio, string downloadPath)
 {
     DownloadAsync(audioCategory, audio.Url, downloadPath).GetAwaiter().GetResult();
 }
コード例 #43
0
 public static Task DownloadAsync(this IAudioCategoryAsync audioCategory, Audio audio, string downloadPath)
 {
     return(DownloadAsync(audioCategory, audio.Url, downloadPath));
 }
コード例 #44
0
    // - Sound play functions -

    // engine start
    public void PlayEngineStartSound()
    {
        Audio.PlaySoundEffect(jetStartEngine, transform.position, 1, 1, transform);
        audioSource.Play();
    }
コード例 #45
0
 private static void NewMusic(string musicName, string filename)
 {
     _music.Add(musicName, Audio.LoadMusic(SwinGame.PathToResource(filename, ResourceKind.SoundResource)));
 }
コード例 #46
0
 private static void NewSound(string soundName, string filename)
 {
     _sounds.Add(soundName, Audio.LoadSoundEffect(SwinGame.PathToResource(filename, ResourceKind.SoundResource)));
 }
コード例 #47
0
 public Task <ItemUpdateType> FetchAsync(Audio item, IDirectoryService directoryService, CancellationToken cancellationToken)
 {
     return(FetchAudioInfo(item, cancellationToken));
 }
コード例 #48
0
 public void PlayRaceFinishedSound()
 {
     Audio.PlaySoundFrontend("RACE_PLACED", "HUD_AWARDS");
 }
コード例 #49
0
 public void PlayRaceBeginSound()
 {
     Audio.PlaySoundFrontend("3_2_1", "HUD_MINI_GAME_SOUNDSET");
 }
コード例 #50
0
 public static string GetName(this Audio audio) => string.Join(" - ", new[] { audio.Artist, audio.Title }.Where(x => !string.IsNullOrEmpty(x)));
コード例 #51
0
ファイル: Game.cs プロジェクト: rfortes/valkyrie
    // Unity fires off this function
    void Awake()
    {
        // save main thread Id
        mainThread = System.Threading.Thread.CurrentThread;

        // Set specific configuration for Android
        if (Application.platform == RuntimePlatform.Android)
        {
            // activate crashlytics
            DebugManager.Enable();

            // deactivate screen timeount while in Valkyrie
            Screen.sleepTimeout = SleepTimeout.NeverSleep;
        }

        // Find the common objects we use.  These are created by unity.
        cc            = GameObject.FindObjectOfType <CameraController>();
        uICanvas      = GameObject.Find("UICanvas").GetComponent <Canvas>();
        boardCanvas   = GameObject.Find("BoardCanvas").GetComponent <Canvas>();
        tokenCanvas   = GameObject.Find("TokenCanvas").GetComponent <Canvas>();
        tokenBoard    = GameObject.FindObjectOfType <TokenBoard>();
        heroCanvas    = GameObject.FindObjectOfType <HeroCanvas>();
        monsterCanvas = GameObject.FindObjectOfType <MonsterCanvas>();

        // Create some things
        uiScaler = new UIScaler(uICanvas);
        config   = new ConfigFile();
        GameObject go = new GameObject("audio");

        audioControl = go.AddComponent <Audio>();
        updateList   = new List <IUpdateListener>();
        stats        = new StatsManager();
        stats.DownloadStats();

        if (config.data.Get("UserConfig") == null)
        {
            // English is the default current language
            config.data.Add("UserConfig", "currentLang", "English");
            config.Save();
        }
        currentLang = config.data.Get("UserConfig", "currentLang");

        string vSet = config.data.Get("UserConfig", "editorTransparency");

        if (vSet == "")
        {
            editorTransparency = 0.3f;
        }
        else
        {
            float.TryParse(vSet, out editorTransparency);
        }

        string s_debug_tests = config.data.Get("Debug", "tests");

        if (s_debug_tests != "")
        {
            s_debug_tests = s_debug_tests.ToLower();
            if (s_debug_tests == "true" || s_debug_tests == "1")
            {
                debugTests = true;
            }
        }

        // On android extract streaming assets for use
        if (Application.platform == RuntimePlatform.Android)
        {
            System.IO.Directory.CreateDirectory(ContentData.ContentPath());
            using (ZipFile jar = ZipFile.Read(Application.dataPath))
            {
                foreach (ZipEntry e in jar)
                {
                    if (!e.FileName.StartsWith("assets"))
                    {
                        continue;
                    }
                    if (e.FileName.StartsWith("assets/bin"))
                    {
                        continue;
                    }

                    e.Extract(ContentData.ContentPath() + "../..", ExtractExistingFileAction.OverwriteSilently);
                }
            }
        }

        DictionaryI18n valDict = new DictionaryI18n();

        foreach (string file in System.IO.Directory.GetFiles(ContentData.ContentPath() + "../text", "Localization*.txt"))
        {
            valDict.AddDataFromFile(file);
        }
        LocalizationRead.AddDictionary("val", valDict);

        roundControl = new RoundController();

        // Read the version and add it to the log
        TextAsset versionFile = Resources.Load("version") as TextAsset;

        version = versionFile.text.Trim();
        // The newline at the end stops the stack trace appearing in the log
        ValkyrieDebug.Log("Valkyrie Version: " + version + System.Environment.NewLine);

#if UNITY_STANDALONE_WIN
        SetScreenOrientationToLandscape();
#endif

        // Bring up the Game selector
        gameSelect = new GameSelectionScreen();
    }
コード例 #52
0
ファイル: Program.cs プロジェクト: Marin-MK/amethyst
        public static void Main(params string[] Args)
        {
            Graphics.Start();
            Audio.Start();
            //BorderlessWindow Window = new BorderlessWindow();
            //Window.Show();

            UIWindow Window = new UIWindow();

            Window.SetBackgroundColor(SystemColors.WindowBackground);

            GroupBox GroupBox1 = new GroupBox(Window.UI.Container);

            GroupBox1.SetPosition(64, 64);
            GroupBox1.SetSize(400, 400);

            Label Label1 = new Label(GroupBox1);

            Label1.SetPosition(16, 21);
            Label1.SetText("Hello world! This is a standard Windows UI label.");

            Button Button1 = new Button(GroupBox1);

            Button1.SetPosition(16, 36);
            Button1.SetText("Start task");
            Button1.OnPressed += delegate(BaseEventArgs e)
            {
                Console.WriteLine($"Clicked button 1!");
                Audio.BGMPlay("D:/Dropbox/Pokemon Jam/Audio/BGM/Battle trainer.ogg", 50, 4);
            };

            Button Button2 = new Button(GroupBox1);

            Button2.SetPosition(16, Button1.Position.Y + Button1.Size.Height + 4);
            Button2.SetText("End task");
            Button2.OnPressed += delegate(BaseEventArgs e) { Console.WriteLine("Clicked button 2!"); };

            CheckBox CheckBox1 = new CheckBox(GroupBox1);

            CheckBox1.SetPosition(16, Button2.Position.Y + Button2.Size.Height + 4);
            CheckBox1.OnCheckChanged += delegate(BaseEventArgs e) { Console.WriteLine("Clicked checkbox 1!"); };

            TabView TabView1 = new TabView(GroupBox1);

            TabView1.SetPosition(130, 46);
            TabView1.SetSize(200, 200);
            TabView1.CreateTab("Autotiles");
            TabView1.CreateTab("Tilesets");
            TabView1.OnTabChanged += delegate(BaseEventArgs e) { Console.WriteLine("Changed tab!"); };

            ListBox ListBox1 = new ListBox(GroupBox1);

            ListBox1.SetPosition(15, CheckBox1.Position.Y + CheckBox1.Size.Height + 10);
            ListBox1.SetSize(100, 200);
            ListBox1.SetItems(new List <ListItem>()
            {
                new ListItem("Alpha"),
                new ListItem("Beta"),
                new ListItem("Gamma"),
                new ListItem("Delta"),
                new ListItem("Epsilon"),
                new ListItem("Zeta"),
                new ListItem("Etha"),
                new ListItem("Iota"),
                new ListItem("Kappa"),
                new ListItem("Labda"),
                new ListItem("Mu"),
                new ListItem("Nu"),
                new ListItem("Xi"),
                new ListItem("Omicron"),
                new ListItem("Pi"),
                new ListItem("Rho"),
                new ListItem("Sigma"),
                new ListItem("Tau"),
                new ListItem("Upsilon"),
                new ListItem("Phi"),
                new ListItem("Chi"),
                new ListItem("Psi"),
                new ListItem("Omega")
            });
            ListBox1.OnSelectionChanged += delegate(BaseEventArgs e)
            {
                Console.WriteLine($"Selection: {ListBox1.SelectedIndex}");
            };

            RadioBox RadioBox1 = new RadioBox(GroupBox1);

            RadioBox1.SetPosition(ListBox1.Position.X, ListBox1.Position.Y + ListBox1.Size.Height + 10);
            RadioBox1.SetText("Is shiny?");
            RadioBox1.OnCheckChanged += delegate(BaseEventArgs e)
            {
                if (RadioBox1.Checked)
                {
                    System.Console.WriteLine("Checked RadioBox 1");
                }
            };
            RadioBox RadioBox2 = new RadioBox(GroupBox1);

            RadioBox2.SetPosition(RadioBox1.Position.X, RadioBox1.Position.Y + RadioBox1.Size.Height + 4);
            RadioBox2.SetText("Is modifiable?");
            RadioBox2.OnCheckChanged += delegate(BaseEventArgs e)
            {
                if (RadioBox2.Checked)
                {
                    System.Console.WriteLine("Checked RadioBox 2");
                }
            };

            Window.Show();

            while (Graphics.CanUpdate())
            {
                Graphics.Update();
            }
            Graphics.Stop();
        }
コード例 #53
0
 public void PlayCheckpointReachedSound()
 {
     Audio.PlaySoundFrontend("3_2_1", "HUD_MINI_GAME_SOUNDSET");
 }
コード例 #54
0
    /// <summary>
    /// Listens for attacks to be completed.
    /// </summary>
    /// <param name="sender">the game</param>
    /// <param name="result">the result of the attack</param>
    /// <remarks>
    /// Displays a message, plays sound and redraws the screen
    /// </remarks>
    private static void AttackCompleted(object sender, AttackResult result)
    {
        bool isHuman;

        isHuman = _theGame.Player == HumanPlayer;

        if (isHuman)
        {
            Message = "You " + result.ToString();
        }
        else
        {
            Message = "The AI " + result.ToString();
        }

        switch (result.Value)
        {
        case var @case when @case == ResultOfAttack.Destroyed:
        {
            PlayHitSequence(result.Row, result.Column, isHuman);
            Audio.PlaySoundEffect(GameSound["Sink"]);
            break;
        }

        case var case1 when case1 == ResultOfAttack.GameOver:
        {
            PlayHitSequence(result.Row, result.Column, isHuman);
            Audio.PlaySoundEffect(GameSound["Sink"]);

            while (Audio.SoundEffectPlaying(GameSound["Sink"]))
            {
                SwinGame.Delay(10);
                SwinGame.RefreshScreen();
            }

            if (HumanPlayer.IsDestroyed)
            {
                Audio.PlaySoundEffect(GameSound["Lose"]);
            }
            else
            {
                Audio.PlaySoundEffect(GameSound["Winner"]);
            }
            break;
        }

        case var case2 when case2 == ResultOfAttack.Hit:
        {
            PlayHitSequence(result.Row, result.Column, isHuman);
            break;
        }

        case var case3 when case3 == ResultOfAttack.Miss:
        {
            PlayMissSequence(result.Row, result.Column, isHuman);
            break;
        }

        case var case4 when case4 == ResultOfAttack.ShotAlready:
        {
            Audio.PlaySoundEffect(GameSound["Error"]);
            break;
        }
        }
    }
コード例 #55
0
 public bool Execute(Request request)
 {
     Audio.NextTrack();
     return(true);
 }
コード例 #56
0
ファイル: OsuGame.cs プロジェクト: hamzaDIT/osu
 protected override void OnActivated()
 {
     base.OnActivated();
     Audio.RemoveAdjustment(AdjustableProperty.Volume, inactiveVolumeAdjust);
 }
コード例 #57
0
ファイル: OsuGame.cs プロジェクト: RondoKnight/osu
        private void load()
        {
            if (!Host.IsPrimaryInstance && !DebugUtils.IsDebugBuild)
            {
                Logger.Log(@"osu! does not support multiple running instances.", LoggingTarget.Runtime, LogLevel.Error);
                Environment.Exit(0);
            }

            if (args?.Length > 0)
            {
                var paths = args.Where(a => !a.StartsWith(@"-")).ToArray();
                if (paths.Length > 0)
                {
                    Task.Run(() => Import(paths));
                }
            }

            dependencies.CacheAs(this);

            dependencies.Cache(SentryLogger);

            dependencies.Cache(osuLogo = new OsuLogo {
                Alpha = 0
            });

            // bind config int to database RulesetInfo
            configRuleset         = LocalConfig.GetBindable <int>(OsuSetting.Ruleset);
            Ruleset.Value         = RulesetStore.GetRuleset(configRuleset.Value) ?? RulesetStore.AvailableRulesets.First();
            Ruleset.ValueChanged += r => configRuleset.Value = r.NewValue.ID ?? 0;

            // bind config int to database SkinInfo
            configSkin = LocalConfig.GetBindable <int>(OsuSetting.Skin);
            SkinManager.CurrentSkinInfo.ValueChanged += skin => configSkin.Value = skin.NewValue.ID;
            configSkin.ValueChanged += skinId =>
            {
                var skinInfo = SkinManager.Query(s => s.ID == skinId.NewValue);

                if (skinInfo == null)
                {
                    switch (skinId.NewValue)
                    {
                    case -1:
                        skinInfo = DefaultLegacySkin.Info;
                        break;

                    default:
                        skinInfo = SkinInfo.Default;
                        break;
                    }
                }

                SkinManager.CurrentSkinInfo.Value = skinInfo;
            };
            configSkin.TriggerChange();

            IsActive.BindValueChanged(active => updateActiveState(active.NewValue), true);

            Audio.AddAdjustment(AdjustableProperty.Volume, inactiveVolumeFade);

            SelectedMods.BindValueChanged(modsChanged);
            Beatmap.BindValueChanged(beatmapChanged, true);
        }
コード例 #58
0
 private void OnSelectionChanged(List <ObjectPicker.RowInfo> selectedRows)
 {
     Audio.StartSound("ui_tertiary_button");
     OnTableChanged();
 }
コード例 #59
0
 private static RawSourceWaveStream AudioToWaveStream(Audio audio)
 {
     return(new RawSourceWaveStream(new MemoryStream(audio.AudioData), new WaveFormat()));
 }
コード例 #60
0
 // engine stop
 public void PlayEngineStopSound()
 {
     audioSource.Stop();
     Audio.PlaySoundEffect(jetStopEngine, transform.position, 1, 1, transform);
 }