Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.IO;
- using UnityEngine;
- namespace RhythmTool.Examples
- {
- /// <summary>
- /// The FileSelector shows a browser and imports a file, before analyzing and playing it.
- /// </summary>
- public class FileSelector : SongSelector
- {
- public Browser browser;
- public AudioImporter importer;
- private string cachePath;
- private string rhythmDataPath;
- void Awake()
- {
- cachePath = Path.Combine(Application.persistentDataPath, "RhythmData");
- if (!Directory.Exists(cachePath))
- Directory.CreateDirectory(cachePath);
- browser.FileSelected += OnFileSelected;
- importer.Loaded += OnLoaded;
- }
- private void OnFileSelected(string path)
- {
- //Hide the browser.
- browser.gameObject.SetActive(false);
- //Start importing the selected song.
- importer.Import(path);
- }
- private void OnLoaded(AudioClip audioClip)
- {
- //Clean up old resources.
- Destroy(player.audioClip);
- Destroy(player.rhythmData);
- //Assign AudioClip
- player.audioClip = audioClip;
- rhythmDataPath = Path.Combine(cachePath, audioClip.name + ".rthm");
- if (File.Exists(rhythmDataPath))
- {
- //If a file is found, load it and start playing the song.
- string json = File.ReadAllText(rhythmDataPath);
- RhythmData rhythmData = ScriptableObjectSerializer.FromJson<RhythmData>(json);
- player.rhythmData = rhythmData;
- StopAllCoroutines();
- StartCoroutine(PlayOnNextFrame());
- }
- else
- {
- //If no RhythmData file was found, analyze the song and save the results when the analysis is done.
- RhythmData rhythmData = analyzer.Analyze(audioClip);
- player.rhythmData = rhythmData;
- StopAllCoroutines();
- StartCoroutine(SaveRhythmData());
- }
- }
- public override void NextSong()
- {
- base.NextSong();
- //Show the browser.
- browser.gameObject.SetActive(true);
- }
- IEnumerator PlayOnNextFrame()
- {
- yield return null;
- player.Play();
- }
- IEnumerator SaveRhythmData()
- {
- while (!analyzer.isDone)
- yield return null;
- RhythmData rhythmData = analyzer.rhythmData;
- string json = ScriptableObjectSerializer.ToJson(rhythmData);
- File.WriteAllText(rhythmDataPath, json);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement