曲に合わせて歌詞を表示したかったので、その方法をメモ。
単純にUpdateに歌詞をテキストに代入する方法だと、微妙にずれてくるので、音楽の再生位置を取得する方法にした。
とはいえ、結局Updateで判定するので完全に同期させるのは無理だった^^
歌詞の配列を作る
ハンプティダンプティの歌詞ですw
string[] lyrics; void Awake () { lyrics = new string[8]; lyrics [0] = "Humpty Dumpty"; lyrics [1] = "sat on a wall"; lyrics [2] = "Humpty Dumpty"; lyrics [3] = "had a great <color=#ff0000ff>FALL."; lyrics [4] = "All the king's horses,"; lyrics [5] = "And all the king's men,"; lyrics [6] = "Couldn't put Humpty"; lyrics [7] = "together again."; }
歌詞を表示する秒数を配列にする
一定間隔なら、配列にする必要もないんだけどw
//メンバ変数 float[] times; //Awakeに追加 times = new float[8]; times [0] = 0.0f; times [1] = 1.4f; times [2] = 2.8f; times [3] = 4.2f; times [4] = 5.6f; times [5] = 7.0f; times [6] = 8.4f; times [7] = 9.8f;
歌詞を表示するテキストを取得しておく
//メンバ変数 public Text title;
再生中かどうかを判定する
Updateを使って歌詞を表示するので、まずは、Updateにて音楽が再生中かどうかを判定する。
void Update () { if (AudioManager.instance.AudioSource_BGM.isPlaying) { } }
現在の再生位置を取得する
AudioManager.instance.AudioSource_BGMは、対象となるAudioSourceになるので、適宜変更すること。
void Update () { if (AudioManager.instance.AudioSource_BGM.isPlaying) { float now = AudioManager.instance.AudioSource_BGM.time; } }
指定した秒数以上なら、歌詞を表示する
int counter = 0; void Update () { if (AudioManager.instance.AudioSource_BGM.isPlaying) { float now = AudioManager.instance.AudioSource_BGM.time; if (counter < lyrics.Length) { if (now >= times [counter]) { title.text = lyrics [counter]; counter++; } } } }