Exemple #1
0
        private IEnumerable <FrequencyDuration> GetNoteFrequencyAndDuration(IEnumerable <string> notes, int a4Ref, IPlayer player, InstrumentType instrument)
        {
            var noteDuration = 0;

            foreach (var noteString in notes)
            {
                string currentNote    = null;
                var    noteInstrument = instrument;
                var    notesParts     = noteString.Split('-');
                if (notesParts.Length > 0)
                {
                    currentNote = notesParts[0];
                }
                if (notesParts.Length > 1)
                {
                    noteDuration = (int)(float.Parse(notesParts[1]));
                }
                if (notesParts.Length > 2)
                {
                    noteInstrument = (InstrumentType)Enum.Parse(typeof(InstrumentType), notesParts[2]);
                }
                if (currentNote.Contains("W", StringComparison.InvariantCultureIgnoreCase))
                {
                    yield return(new FrequencyDuration("W", 0, 0F, noteDuration));
                }
                else
                {
                    var musicNote = MusicNote.Create(currentNote, a4Ref, player, noteDuration, noteInstrument);
                    yield return(new FrequencyDuration(musicNote.Key, musicNote.DesiredOctave, musicNote.CurrentFrequency, noteDuration));
                }
            }
        }
        private static (MusicalSymbolDuration Duration, int Dots) TranslateDuration(MusicNote note)
        {
            switch (note.Duration)
            {
            case 1:
                return(MusicalSymbolDuration.Sixteenth, 0);

            case 2:
                return(MusicalSymbolDuration.Eighth, 0);

            case 4:
                return(MusicalSymbolDuration.Quarter, 0);

            case 6:
                return(MusicalSymbolDuration.Eighth, 1);

            case 8:
                return(MusicalSymbolDuration.Half, 0);

            case 16:
                return(MusicalSymbolDuration.Whole, 0);

            default:
                throw new ArgumentException($"Don't know how to translate {note.Duration}/16ths of a note.");
            }
        }
        public BaseNote getNote(int duration, string pitch, int octave, bool dotted = false)
        {
            MusicNote note = new MusicNote();

            char[] pitchArray = pitch.ToCharArray();

            if (pitchArray.Length > 0)
            {
                note.Pitch = pitchArray[0];
            }

            if (pitchArray.Length >= 3 && pitchArray[1] == 'i')
            {
                note.PitchModifier = PitchModifier.Sharp;
            }
            else if (pitchArray.Length >= 3 && pitchArray[1] == 'e')
            {
                note.PitchModifier = PitchModifier.Flat;
            }
            else
            {
                note.PitchModifier = PitchModifier.None;
            }

            note.Duration = 1.0f / duration;
            note.Dotted   = dotted;
            note.Octave   = octave;

            return(note);
        }
Exemple #4
0
    private void assetload()
    {
        /*MusicInstruments tool = new MusicInstruments();
         * tool.MI_Add(SD4);
         * tool.MI_Add(SD5);*/

        AssetBundle _notetest = AssetBundle.LoadFromFile("AssetBundles/notetest");

        GameObject[] notearry = _notetest.LoadAllAssets <GameObject>();
        MusicNote    _note    = new MusicNote();

        foreach (GameObject c in notearry)
        {
            _note.MN_Add(c);
        }

        AssetBundle _tooltest = AssetBundle.LoadFromFile("AssetBundles/toolstest");

        GameObject[]     toolarry = _tooltest.LoadAllAssets <GameObject>();
        MusicInstruments _tools   = new MusicInstruments();

        foreach (GameObject c in toolarry)
        {
            _tools.MI_Add(c);
        }
    }
        public void visit(MusicNote m)
        {
            // Calculate duration
            double absoluteLength = m.Duration;

            double relationToQuartNote  = _beatNote / 4.0;
            double percentageOfBeatNote = (1.0 / _beatNote) / absoluteLength;
            double deltaTicks           = (sequence.Division / relationToQuartNote) / percentageOfBeatNote;

            string pitch = m.Pitch.ToString();

            if (m.PitchModifier == PitchModifier.Flat)
            {
                pitch += "es";
            }
            if (m.PitchModifier == PitchModifier.Sharp)
            {
                pitch += "is";
            }

            // Calculate height
            int noteHeight = notesOrderWithCrosses.IndexOf(m.Pitch.ToString()) + ((m.Octave) * 12);

            //noteHeight += note.Alter;
            notesTrack.Insert(absoluteTicks, new ChannelMessage(ChannelCommand.NoteOn, 1, noteHeight, 90)); // Data2 = volume

            absoluteTicks += (int)deltaTicks;
            notesTrack.Insert(absoluteTicks, new ChannelMessage(ChannelCommand.NoteOn, 1, noteHeight, 0)); // Data2 = volume
        }
    Notes InitNotes(MusicNote musicNote)     //ノーツの初期化
    {
        var Note       = Instantiate(NoteObj, NoteArea.transform);
        var NoteScript = Note.GetComponent <Notes>();        //ノーツのスクリプトを読み込む

        NoteScript.Score = new MusicNote()
        {
            NoteType = Rest
        };
        NoteScript.TapID          = -1;
        NoteScript.Speed          = GameManager4.SetSpeed(Settings.NotesSpeed);   //ノーツのスピード
        NoteScript.TargetString   = Astring;                                      //ノーツの降る弦を取得する
        NoteScript.TargetPosition = new Vector2(-3200 + 1600f / 12 * 7, 70 + 75); //ノーツのターゲット位置を取得する
        NoteScript.StartPosition  = new Vector2(700, 250 + 75);
        Note.GetComponent <RectTransform>().anchoredPosition = NoteScript.StartPosition;
        //ノーツのスタートする位置を設定する
        NoteScript.Score = musicNote;         //ノーツの種類
        NoteScript.Size  = Settings.Size;
        var effect = Instantiate(JudgeEffect, EffectArea.transform);

        NoteScript.Effect = effect.GetComponent <JudgeEffect>();
        if (Settings.ShowScale)
        {
            effect.GetComponentInChildren <Text>().text = GameManager4.Pitches[(int)musicNote.PitchStep][musicNote.Alter + 1];
        }
        else
        {
            effect.GetComponentInChildren <Text>().enabled = false;
        }
        NoteScript.PlayingAuto = true;
        NoteScript.Judge       = Judge;
        effect.GetComponent <RectTransform>().anchoredPosition = NoteScript.TargetPosition + Vector2.up * 50;
        return(NoteScript);
    }
        private void play_note(MusicNote note)
        {
            SoundPlayer player = new SoundPlayer(@"C:\Users\Callum\source\repos\LogisUniWork\LogisUniWork\Sounds\{0}.wav".Replace("{0}", note.pitch.ToString()));

            player.Play();
            System.Threading.Thread.Sleep(note.noteDuration);
        }
    void PlayerInputted()
    {
        // Start the song if it isn't started yet.
        if (!songStarted)
        {
            songStarted = true;
            StartSong();
            statusText.text = "";
            return;
        }

        // Play the beat sound.
        beatAudioSource.Play();

        if (notesOnScreen.Count > 0)
        {
            // Get the front note.
            MusicNote frontNote = notesOnScreen.Peek();

            // Distance from the note to the finish line.
            float offset = Mathf.Abs(frontNote.gameObject.transform.position.x - finishLineX);

            // Music note hit.
            if (offset <= tolerationOffset)
            {
                // Change color to green to indicate a "HIT".
                frontNote.ChangeColor(true);

                statusText.text = "HIT!";

                // Remove the reference. (Now the next note moves to the front of the queue.)
                notesOnScreen.Dequeue();
            }
        }
    }
Exemple #9
0
        private void DoWork()
        {
            MusicNote note = null;

            while (true)
            {
                lock (this.syncRoot) {
                    if (this.playlist.Count == 0)
                    {
                        break;
                    }

                    note = (MusicNote)this.playlist.Dequeue();
                }

                if (note.Tone.Frequency != 0.0)
                {
                    this.pwm.Controller.SetDesiredFrequency((int)note.Tone.Frequency);
                    this.pwm.SetActiveDutyCyclePercentage(0.5);
                    //tambahan
                    this.pwm.Start();
                    //.Set((int)note.Tone.Frequency, 0.5);
                }
                else
                {
                    this.pwm.Stop();//.IsActive = false;
                }

                Thread.Sleep(note.Duration);
            }

            this.pwm.Controller.SetDesiredFrequency(100.0);
            this.pwm.SetActiveDutyCyclePercentage(0.0001);//Set(100.0, 0.0001);
        }
Exemple #10
0
    int GetFrequencyFromPosition(Vector2 pos)
    {
        var StPos = Strings.Select((s, index) =>
                                   ((s.GetComponent <RectTransform>().anchoredPosition + ViolinRect.anchoredPosition).y, index))
                    .OrderBy(s => Math.Abs(pos.y - s.y)).FirstOrDefault();
        var Opens = new MusicNote[] {
            new MusicNote()
            {
                PitchStep = Pitch.G, Octave = 3
            },
            new MusicNote()
            {
                PitchStep = Pitch.D, Octave = 4
            },
            new MusicNote()
            {
                PitchStep = Pitch.A, Octave = 4
            },
            new MusicNote()
            {
                PitchStep = Pitch.E, Octave = 5
            },
        };

        pos -= ViolinRect.anchoredPosition;
        //var pit2e = pos.x / CanvasRect.rect.width / 2 + 1d / 4d - 1d / 24d + 1;
        var pit2e = (pos.x / CanvasRect.rect.width / 2 + 1d / 4d + 1) * Settings.Division / 6 - 1d / 24d;
        //	var pit = Opens[StPos.index].GetFrequency() * Math.Pow(2, Math.Round(pit2e * 12) / 12);
        var pit = Opens[StPos.index].GetFrequency() * Math.Pow(2, pit2e);

        return((int)pit);
    }
Exemple #11
0
 private static void PlayNoteAsRequired(string note, int a4Reference, PlayableSequence playableSequence)
 {
     if (note != null)
     {
         var musicNote = MusicNote.Create(note, a4Reference);
         if (musicNote?.IsValid ?? false)
         {
             ShowNote(musicNote);
             var musicNotes = musicNote.MajorScale.ToArray();
             WriteMessage($"Playing Major Scale: {string.Join(',', musicNotes)}");
             playableSequence.LoadSequenceFromString(musicNote.MajorScale);
             playableSequence.Prepare();
             playableSequence.Play();
             Thread.Sleep(1000);
             musicNotes = musicNote.MinorScale.ToArray();
             WriteMessage($"Playing Minor Scale: {string.Join(',', musicNotes)}");
             playableSequence.LoadSequenceFromString(musicNote.MinorScale);
             playableSequence.Prepare();
             playableSequence.Play();
             Thread.Sleep(1000);
             WriteMessage($"Playing Relative Minor Scale {musicNote.RelativeMinor}m: {string.Join(',', musicNote.RelativeMinorScale)}");
             playableSequence.LoadSequenceFromString(musicNote.RelativeMinorScale);
             playableSequence.Prepare();
             playableSequence.Play();
         }
         else
         {
             WriteMessage($"{note} is NOT a valid note!", ConsoleColor.Red);
         }
     }
 }
Exemple #12
0
        private void DoWork()
        {
            MusicNote note = null;

            while (true)
            {
                lock (this.syncRoot) {
                    if (this.playlist.Count == 0)
                    {
                        break;
                    }

                    note = (MusicNote)this.playlist.Dequeue();
                }

                if (note.Tone.Frequency != 0.0)
                {
                    this.pwm.Set((int)note.Tone.Frequency, 0.5);
                }
                else
                {
                    this.pwm.IsActive = false;
                }

                Thread.Sleep(note.Duration);
            }

            this.pwm.Set(100.0, 0.0001);
        }
Exemple #13
0
    public void CreateMusicNotes()
    {
        //a0-7 b0-7 c1-8
        float offsetX = 0;

        string[] zeroToseven = { "A", "B" };
        for (int i = 0; i < zeroToseven.Length; i++)
        {
            for (int j = 0; j < 8; j++)
            {
                MusicNote temp = Instantiate(musicPrefab, new Vector3(i * 2.0F, 0, j * 2.0F), Quaternion.identity);
                temp.tone  = zeroToseven[i] + j;
                temp.color = new Color(i, 0, i + 1);
                musicNotes.Add(temp);
                offsetX = i * 2.0F;
            }
        }

        offsetX *= 2;
        float placement = offsetX;

        for (int i = 1; i < 9; i++)
        {
            MusicNote temp = Instantiate(musicPrefab, new Vector3(placement, 0, (i * 2) - 2), Quaternion.identity);
            temp.tone  = "C" + i;
            temp.color = new Color(i, i * 2, i + 1);
            musicNotes.Add(temp);
        }

        offsetX += 2;
        //d e f g 1-7
        string[] oneToSeven = { "D", "E", "F", "G" };

        for (int i = 0; i < oneToSeven.Length; i++)
        {
            for (int j = 1; j < 8; j++)
            {
                MusicNote temp = Instantiate(musicPrefab, new Vector3((i * 2.0F) + offsetX, 0, j * 2.0F), Quaternion.identity);
                temp.tone  = oneToSeven[i] + j;
                temp.color = new Color(i * 2, 0, 1);
                musicNotes.Add(temp);
            }
        }

        offsetX = (offsetX * 2) + 2;

        string[] oneToSix = { "A#", "C#", "D#", "F#", "G#" };

        for (int i = 0; i < oneToSix.Length; i++)
        {
            for (int j = 1; j < 8; j++)
            {
                MusicNote temp = Instantiate(musicPrefab, new Vector3((i * 2.0F) + offsetX, 0, j * 2.0F), Quaternion.identity);
                temp.tone  = oneToSix[i] + j;
                temp.color = new Color(i + 2, i, i + 1);
                musicNotes.Add(temp);
            }
        }
    }
Exemple #14
0
        public override void Load(string filePath)
        {
            _curTime = 0;
            _points.Clear();
            load(filePath);

            foreach (Note n in _notes)
            {
                if (n.ToneIdx >= 0)
                {
                    double pLen = n.Length;
                    if (n.LenRatio >= 0 && n.LenRatio < 8) pLen *= n.LenRatio / 8.0;

                    MusicNote onNote = new MusicNote();
                    onNote.Pitch = ToneAnalyzer.PitchFromTone(n.ToneIdx, n.Octave);
                    onNote.Start = true;
                    onNote.TimeInSec = _curTime;
                    _points.Add(onNote);

                    MusicNote offNote = new MusicNote();
                    offNote.Pitch = onNote.Pitch;
                    offNote.Start = false;
                    offNote.TimeInSec = _curTime + pLen;
                    _points.Add(offNote);

                    if (_maxP < onNote.Pitch) _maxP = onNote.Pitch;
                    if (_minP > onNote.Pitch) _minP = onNote.Pitch;
                }
                _curTime += n.Length;
            }

            Length = _curTime;

            ToneResult minTone = ToneAnalyzer.Analyze(_minP, 1.0);
            ToneResult maxTone = ToneAnalyzer.Analyze(_maxP, 1.0);

            maxTone.ToneIdx++;
            if (maxTone.ToneIdx >= 12) { maxTone.ToneIdx -= 12; maxTone.Octave++; }
            minTone.ToneIdx--;
            if (minTone.ToneIdx <= 0) { minTone.ToneIdx += 12; minTone.Octave--; }

            MinPitch = ToneAnalyzer.PitchFromTone(minTone.ToneIdx, minTone.Octave);
            MaxPitch = ToneAnalyzer.PitchFromTone(maxTone.ToneIdx, maxTone.Octave);

            _points.Sort((MusicNote n1, MusicNote n2) =>
            {
                if (n1.TimeInSec != n2.TimeInSec) return n1.TimeInSec.CompareTo(n2.TimeInSec);
                if (n1.Start)
                {
                    if (n2.Start) return 0;
                    return 1;
                }
                else
                {
                    if (n2.Start) return -1;
                    return 0;
                }
            });
        }
        public void visit(MusicNote n)
        {
            // Length
            //int noteLength = Int32.Parse(Regex.Match(currentToken.Value, @"\d+").Value);
            float noteLength = 1 / n.Duration;

            // Crosses and Moles
            int alter = 0;

            //alter += Regex.Matches(currentToken.Value, "is").Count;
            //alter -= Regex.Matches(currentToken.Value, "es|as").Count;

            if (n.PitchModifier == PitchModifier.Sharp)
            {
                alter++;
            }
            if (n.PitchModifier == PitchModifier.Flat)
            {
                alter--;
            }


            // Octaves
            //int distanceWithPreviousNote = notesorder.IndexOf(currentToken.Value[0]) - notesorder.IndexOf(previousNote);
            //if (distanceWithPreviousNote > 3) // Shorter path possible the other way around
            //{
            //    distanceWithPreviousNote -= 7; // The number of notes in an octave
            //}
            //else if (distanceWithPreviousNote < -3)
            //{
            //    distanceWithPreviousNote += 7; // The number of notes in an octave
            //}

            //if (distanceWithPreviousNote + notesorder.IndexOf(previousNote) >= 7)
            //{
            //    previousOctave++;
            //}
            //else if (distanceWithPreviousNote + notesorder.IndexOf(previousNote) < 0)
            //{
            //    previousOctave--;
            //}

            //// Force up or down.
            //previousOctave += currentToken.Value.Count(c => c == '\'');
            //previousOctave -= currentToken.Value.Count(c => c == ',');

            previousNote = n;

            var note = new Note(n.Pitch.ToString().ToUpper(), alter, n.Octave, (MusicalSymbolDuration)noteLength, NoteStemDirection.Up, NoteTieType.None, new List <NoteBeamType>()
            {
                NoteBeamType.Single
            });

            //note.NumberOfDots += currentToken.Value.Count(c => c.Equals('.'));
            note.NumberOfDots += (n.Dotted) ? 1 : 0;

            symbolBuffer = note;
        }
Exemple #16
0
    private void AddMusicNote(long insertTime, string wavId)
    {
        MusicNote musicNote = new MusicNote(insertTime, wavId);

        if (audioClips.ContainsKey(wavId))
        {
            musicNotes.Add(musicNote);
        }
    }
        public MusicNote CreateNote(int pitch, int noteType, int noteDuration)
        {
            MusicNote note = new MusicNote();

            note.pitch        = pitch;
            note.noteType     = noteType;
            note.noteDuration = noteDuration;
            return(note);
        }
 public InstrumentComponent()
 {
     _unshiftedNote = MusicNote.FromNoteNumber(0);
     FineTune = 0;
     Gain = 0;
     LowNote = 0;
     HighNote = 127;
     LowVelocity = 1;
     HighVelocity = 127;
 }
 public override void Read(BinaryReader reader)
 {
     _unshiftedNote = MusicNote.FromNoteNumber(reader.ReadSByte());
     FineTune       = reader.ReadSByte();
     Gain           = reader.ReadSByte();
     LowNote        = reader.ReadSByte();
     HighNote       = reader.ReadSByte();
     LowVelocity    = reader.ReadSByte();
     HighVelocity   = reader.ReadSByte();
 }
 public InstrumentComponent()
 {
     _unshiftedNote = MusicNote.FromNoteNumber(0);
     FineTune       = 0;
     Gain           = 0;
     LowNote        = 0;
     HighNote       = 127;
     LowVelocity    = 1;
     HighVelocity   = 127;
 }
    void Update()
    {
        // Check key press.
        if (Input.GetKeyDown(KeyCode.Space))
        {
            PlayerInputted();
        }

        if (!songStarted)
        {
            return;
        }

        // Calculate songposition. (Time passed - time passed last frame).
        songposition = (float)(AudioSettings.dspTime - dsptimesong - songOffset);

        // Check if we need to instantiate a new note. (We obtain the current beat of the song by (songposition / secondsPerBeat).)
        // See the image for note spawning (note that the direction is reversed):
        // http://shinerightstudio.com/posts/music-syncing-in-rhythm-games/pic2.png
        float beatToShow = songposition / secondsPerBeat + BeatsShownOnScreen;

        // Check if there are still notes in the track, and check if the next note is within the bounds we intend to show on screen.
        if (indexOfNextNote < track.Length && track[indexOfNextNote] < beatToShow)
        {
            // Instantiate a new music note. (Search "Object Pooling" for more information if you wish to minimize the delay when instantiating game objects.)
            // We don't care about the position and rotation because we will set them later in MusicNote.Initialize(...).
            MusicNote musicNote = ((GameObject)Instantiate(musicNotePrefab, Vector2.zero, Quaternion.identity)).GetComponent <MusicNote>();

            musicNote.Initialize(this, startLineX, finishLineX, removeLineX, posY, track[indexOfNextNote]);

            // The note is push into the queue for reference.
            notesOnScreen.Enqueue(musicNote);

            // Update the next index.
            indexOfNextNote++;
        }

        // Loop the queue to check if any of them reaches the finish line.
        if (notesOnScreen.Count > 0)
        {
            MusicNote currNote = notesOnScreen.Peek();

            if (currNote.transform.position.x >= finishLineX + tolerationOffset)
            {
                // Change color to red to indicate a miss.
                currNote.ChangeColor(false);

                notesOnScreen.Dequeue();

                statusText.text = "MISS!";
            }
        }

        // Note that the music note is eventually removed by itself (the Update() function in MusicNote) when it reaches the removeLine.
    }
    private void Awake()
    {
        if (inGameManager.editMode == false)
        {
            musicNum = GameManager.Instance.playMusicNum;
        }

        nowMusicNode             = musicNode[musicNum];
        inGameManager.music.clip = nowMusicNode.music;
        inGameManager.speed      = GameManager.Instance.GetSpeed();
    }
Exemple #23
0
 void Start()
 {
     musicNote      = GameObject.Find("Img_bg").GetComponent <MusicNote>();
     startNote      = GetComponent <Image>();      //音乐节节点
     player_onclick = GameObject.Find("Btn_player").GetComponent <Button>();
     player_onclick.onClick.AddListener(CheckRay); //点击监听
     targetNote = GameObject.Find("Img_trigger");
     missNote   = GameObject.Find("Img_miss");
     score      = GameObject.Find("Txt_score").GetComponent <Text>();
     miss       = GameObject.Find("Txt_miss").GetComponent <Text>();
 }
 public static byte[] CreateTone(MusicNote note, TimeSpan duration, PCMModifiers mods)
 {
     mods.Init();
     using (MemoryStream stream = new MemoryStream()) {
         BinaryWriter writer = new BinaryWriter(stream);
         WriteNote(writer,
                   new MidiNote()
         {
             Note     = note,
             Duration = duration,
         }, mods);
         return(stream.ToArray());
     }
 }
    /// <summary>
    /// Public method that checks to see if the timeline ticker is near a music note / drum beat. We use 1/4 of a second buffer range between
    /// the given time stamp and the timeline ticker.
    ///
    /// If the timeline ticker is near the music note, indicate to the music note that the music note has been touched.
    ///
    /// However, it is the timeline ticker's job to get data from the AR Face to see if a successful nod
    /// has been made.
    /// </summary>
    /// <returns></returns>
    public bool isTimelineTickerNearMusicNote(out MusicNote mNote)
    {
        float currentTime = timelineTicker.currentTime;

        foreach (MusicNoteGameObject musicNote in currentMusicNotesInTimeline)
        {
            if (currentTime >= musicNote.musicNoteData.TimeStamp - drumHitThreshold & currentTime <= musicNote.musicNoteData.TimeStamp)
            {
                mNote = musicNote.musicNoteData;
                return(true);
            }
        }
        mNote = null;
        return(false);
    }
Exemple #26
0
    int GetTargetStringIndexFromNotes(MusicNote Note)
    {
        if (Note.String != Pitch.C)
        {
            return(Note.String == Pitch.G ? 0 : (Note.String == Pitch.D ? 1 : (Note.String == Pitch.A ? 2 : 3)));
        }
        int pitch    = Note.GetPitch();
        int pitchStr = (pitch - 43) / 7;

        if (pitchStr >= 4)
        {
            pitchStr = 3;
        }
        return(pitchStr);
    }
Exemple #27
0
        private static void ShowNote(MusicNote musicNote)
        {
            var relativeMinor = musicNote.RelativeMinor;
            var relativeMajor = musicNote.RelativeMajor;

            WriteMessage($"{musicNote} is the current note");
            WriteMessage($"Frequencies for this note are: {string.Join(',', musicNote.Frequencies.Select(f => f.ToString()))}");
            WriteMessage($"Of the 12 natural, flat and sharp notes {musicNote} has {musicNote.NoteBefore} before it and {musicNote.NoteAfter} after it.");
            WriteMessage($"Of the 7 notes in the {musicNote} scale {musicNote} has {musicNote.MajorNoteBefore} before it and {musicNote.MajorNoteAfter} after it.");
            WriteMessage($"Of the 7 notes in the {musicNote}m scale {musicNote} has {musicNote.MinorNoteBefore} before it and {musicNote.MinorNoteAfter} after it.");
            WriteMessage($"Notes in {musicNote} are: {string.Join(',', musicNote.MajorScale)}");
            WriteMessage($"Notes in {musicNote}m are: {string.Join(',', musicNote.MinorScale)}");
            WriteMessage($"Major Chord: {string.Join(',', musicNote.MajorChord15)} minor Chord: {string.Join(',', musicNote.MinorChord15)}");
            WriteMessage($"The relative minor is {relativeMinor}m");
            WriteMessage($"The relative minor scale is {string.Join(',', musicNote.RelativeMinorScale)}");
            WriteMessage($"The relative Major to the minor is {relativeMajor}");
        }
        private static (string Note, int Alter, int Octave) TranslateNote(MusicNote note)
        {
            var octave = note.Note / 12 - 1;

            switch (note.Note % 12)
            {
            case 0:
                return("C", 0, octave);

            case 1:
                return("C", 1, octave);

            case 2:
                return("D", 0, octave);

            case 3:
                return("D", 1, octave);

            case 4:
                return("E", 0, octave);

            case 5:
                return("F", 0, octave);

            case 6:
                return("F", 1, octave);

            case 7:
                return("G", 0, octave);

            case 8:
                return("G", 1, octave);

            case 9:
                return("A", 0, octave);

            case 10:
                return("A", 1, octave);

            case 11:
                return("B", 0, octave);

            default:
                throw new Exception("Unreachable code!");
            }
        }
Exemple #29
0
        /// <summary>
        /// The function that runs when the playback thread is started. Returns (ends the thread) when playback is finished or Stop() is called.
        /// </summary>
        private void PlaybackThread()
        {
            while (this.running && playList.NotesRemaining > 0)
            {
                // Get the next note.
                MusicNote currNote = playList.GetNextNote();

                // Set the tone and sleep for the duration
                SetTone(currNote.tone);

                Thread.Sleep(currNote.duration);
            }

            SetTone(Tone.Rest);

            this.running = false;
        }
    public bool isTimelineTickerPastMusicNote(out MusicNote mNote)
    {
        float currentTime = timelineTicker.currentTime;

        foreach (MusicNoteGameObject musicNote in currentMusicNotesInTimeline)
        {
            if (currentTime >= musicNote.musicNoteData.TimeStamp & currentTime <= (musicNote.musicNoteData.TimeStamp + drumHitThreshold))
            {
                Debug.Log("It is past the music note");
                mNote = musicNote.musicNoteData;
                return(true);
            }
        }
        Debug.Log("it is not past the music note");
        mNote = null;
        return(false);
    }
Exemple #31
0
    public void GetAbsoluteTimes(int trackIndex)
    {
        //just to save on line length
        Track currentTrack = currentSong.tracks[trackIndex];

        //propogetes the "game time" property of Notes (in s), relative to Clock.Instance.Time
        for (int k = 0; k < currentTrack.notes.Length; k++)
        {
            currentTrack.notes[k].gameTime = ((currentTrack.notes[k].beatTime) * timeScale * 60f / (float)Clock.Instance.BPM);
        }
        if (currentTrack.notes[currentTrack.notes.Length - 1].gameTime > timeOfLastNote)
        {
            lastNote       = currentTrack.notes[currentTrack.notes.Length - 1];
            timeOfLastNote = currentTrack.notes[currentTrack.notes.Length - 1].gameTime;
            Debug.Log("time of last note = " + timeOfLastNote);
            _beatOfLastNote = currentTrack.notes[currentTrack.notes.Length - 1].beatTime;
        }
        //Debug.Log(timeOfLastNote);
    }
Exemple #32
0
    public override IEnumerator AttackLong()
    {
        attackTimer = 0.0f;
        while (attackTimer < LONG_ATTACK_WINDUP)
        {
            attackTimer += Time.deltaTime;
            yield return(null);
        }

        // Create projectile (musicNote)
        GameObject mNote = Instantiate(musicNote,
                                       transform.parent.position + new Vector3(0, 0.1f), Quaternion.identity);
        MusicNote mnScript = mNote.GetComponent <MusicNote>();

        mnScript.playerRotationY   = transform.parent.rotation.y;
        mnScript.startTime         = (float)rand.NextDouble() * 0.4f;
        mnScript.oscillationPeriod = (float)rand.NextDouble() * 1.5f + 2.5f;
        mnScript.setSpeed((float)rand.NextDouble() * 1.8f + 5.8f);
        mNote.SetActive(true);
    }
 public override void Read(BinaryReader reader)
 {
     _unshiftedNote = MusicNote.FromNoteNumber(reader.ReadSByte());
     FineTune = reader.ReadSByte();
     Gain = reader.ReadSByte();
     LowNote = reader.ReadSByte();
     HighNote = reader.ReadSByte();
     LowVelocity = reader.ReadSByte();
     HighVelocity = reader.ReadSByte();
 }
		/// <summary>
		/// 譜面情報をデシリアライズします
		/// </summary>
		/// <param name="scoreFilePath">譜面のファイルパス</param>
		/// <returns></returns>
		public static async Task<MusicScore> DeserializeAsync(string scoreFilePath)
		{
			MusicScore score;

			string jStr = "";

			if (!File.Exists(scoreFilePath))
				throw new ArgumentException($"score file not found (filePath: {scoreFilePath})");

			using (var sr = new StreamReader(scoreFilePath))
				jStr = await sr.ReadToEndAsync();

			var json = DynamicJson.Parse(jStr);

			var scoreVersion = json.meta.score_version;

			if (scoreVersion == 1.0)
			{
				string title = json.meta.title;
				double bpm = json.meta.bmp;
				string songUrl = json.meta.song_url;
				double offset = json.meta.offset;

				score = new MusicScore(title, (int)bpm, new Uri(songUrl), 4, offset);

				foreach (var tags in json.meta.tags)
				{
					score.Tags.Add((string)tags);
				}

				foreach (var bar in json.bars)
				{
					var size = ((string)bar.size).Split(':').ToList();

					var count = int.Parse(size[0]);
					var span = size.Count == 2 ? double.Parse(size[1]) : 1.0;

					var musicBar = new MusicBar(score, count, span);

					foreach (var lane in bar.notes)
					{
						var musicLane = new MusicLane(musicBar);

						foreach (string noteInfo in lane)
						{
							var noteInfoList = noteInfo.Split(':');
							var countLocation = int.Parse(noteInfoList[0]);
							var noteType = (MusicNoteType)int.Parse(noteInfoList[1]);

							var musicNote = new MusicNote(countLocation, musicLane, noteType);

							musicLane.Notes.Add(musicNote);
						}

						musicBar.Lanes.Add(musicLane);
					}

					score.Bars.Add(musicBar);
				}
			}
			else
			{
				throw new ArgumentException($"Unknown score version (value: {scoreVersion})");
			}

			return score;
		}
Exemple #35
0
        public override void Load(string filePath)
        {
            List<List<TrackEvent>> trackEvents = new List<List<TrackEvent>>();
            BinaryReader reader = new BinaryReader(new FileStream(filePath, FileMode.Open), Encoding.UTF8);

            _header = readHeader(reader);
            if (!_header.DeltaTimeInPPQN) throw new SMFException("対応していないMIDIファイル:TimeInSec Division");
            if (_header.FormatType == 2) throw new SMFException("対応していないMIDIファイル:Format");

            for (int i = 0; i < _header.TrackNum; i++)
            {
                List<TrackEvent> evs = new List<TrackEvent>();
                readTrack(reader, ref evs);
                trackEvents.Add(evs);
            }

            double maxPitch = double.MinValue;
            double minPitch = double.MaxValue;

            long prevTick = 0;
            double time = 0;
            int tempo = 500000;
            double ppqnInv = 1 / (double)_header.DeltaTime;
            Dictionary<int, Dictionary<int, SMFNote>> channels = new Dictionary<int, Dictionary<int, SMFNote>>();

            _points = new List<MusicNote>();
            while (true)
            {
                if (trackEvents.Count == 0) break;
                if (trackEvents.TrueForAll((lst) => { return lst.Count == 0; })) break;

                int idx = -1; long minTick = long.MaxValue;
                for (int i = 0; i < trackEvents.Count; i++)
                {
                    if (trackEvents[i].Count == 0) continue;
                    long tick = trackEvents[i][0].AbsoluteTick;
                    if (tick < minTick) { idx = i; minTick = tick; }
                }

                if (idx < 0) break;

                TrackEvent fstev = trackEvents[idx][0];
                trackEvents[idx].RemoveAt(0);
                time += (fstev.AbsoluteTick - prevTick) * tempo * ppqnInv / 1000000.0;
                
                switch (fstev.EventType)
                {
                    case EventType.Tempo:
                        tempo = (int)fstev.Params[0];
                        break;
                    case EventType.NoteOn:
                        {
                            int channel = (int)fstev.Params[0];
                            int noteNum = (int)fstev.Params[1];

                            Dictionary<int, SMFNote> noteNums;
                            if (channels.ContainsKey(channel))
                            {
                                noteNums = channels[channel];
                            }
                            else
                            {
                                noteNums = new Dictionary<int, SMFNote>();
                                channels.Add(channel, noteNums);
                            }

                            SMFNote note;
                            if (noteNums.ContainsKey(noteNum))
                            {
                                note = noteNums[noteNum];

                                MusicNote n = new MusicNote();
                                n.TimeInSec = time;
                                n.Pitch = note.Pitch;
                                n.Start = false;
                                _points.Add(n);
                            }

                            note = new SMFNote(true, pitchFromNote(noteNum));
                            if (noteNums.ContainsKey(noteNum))
                                noteNums[noteNum] = note;
                            else
                                noteNums.Add(noteNum, note);

                            MusicNote nn = new MusicNote();
                            nn.TimeInSec = time;
                            nn.Pitch = note.Pitch;
                            nn.Start = true;
                            _points.Add(nn);

                            if (note.Pitch < minPitch) minPitch = note.Pitch;
                            if (note.Pitch > maxPitch) maxPitch = note.Pitch;
                        }
                        break;
                    case EventType.NoteOff:
                        {
                            int channel = (int)fstev.Params[0];
                            int noteNum = (int)fstev.Params[1];

                            Dictionary<int, SMFNote> noteNums;
                            if (channels.ContainsKey(channel))
                            {
                                noteNums = channels[channel];
                            }
                            else
                            {
                                noteNums = new Dictionary<int, SMFNote>();
                                channels.Add(channel, noteNums);
                            }

                            SMFNote note;
                            if (noteNums.ContainsKey(noteNum))
                            {
                                note = noteNums[noteNum];

                                MusicNote n = new MusicNote();
                                n.TimeInSec = time;
                                n.Pitch = note.Pitch;
                                n.Start = false;
                                _points.Add(n);

                                if (note.Pitch < minPitch) minPitch = note.Pitch;
                                if (note.Pitch > maxPitch) maxPitch = note.Pitch;

                                noteNums.Remove(noteNum);
                            }
                        }
                        break;
                }

                prevTick = fstev.AbsoluteTick;
            }

            _length = time;
            
            ToneResult minTone = ToneAnalyzer.Analyze(minPitch, 1.0);
            ToneResult maxTone = ToneAnalyzer.Analyze(maxPitch, 1.0);

            maxTone.ToneIdx++;
            if (maxTone.ToneIdx >= 12) { maxTone.ToneIdx -= 12; maxTone.Octave++; }
            minTone.ToneIdx--;
            if (minTone.ToneIdx <= 0) { minTone.ToneIdx += 12; minTone.Octave--; }

            MinPitch = ToneAnalyzer.PitchFromTone(minTone.ToneIdx, minTone.Octave);
            MaxPitch = ToneAnalyzer.PitchFromTone(maxTone.ToneIdx, maxTone.Octave);

            _points.Sort((MusicNote n1, MusicNote n2) =>
            {
                if (n1.TimeInSec != n2.TimeInSec) return n1.TimeInSec.CompareTo(n2.TimeInSec);
                if (n1.Start)
                {
                    if (n2.Start) return 0;
                    return 1;
                }
                else
                {
                    if (n2.Start) return -1;
                    return 0;
                }
            });
        }