aeroson

Untitled

May 16th, 2020
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using UnityEngine;
  7. using RuntimeAudioClipLoader;
  8. using System.Collections.Generic;
  9.  
  10. namespace RuntimeAudioClipLoaderDemo
  11. {
  12. public class LoadAllStreamingAssets : MonoBehaviour
  13. {
  14. static string rootFolder { get { return Application.streamingAssetsPath; } }
  15. static string sourceFolder { get { return Path.Combine(rootFolder, "RuntimeAudioClipLoader"); } }
  16.  
  17.  
  18. public List<string> streamingAssetPathsToLoad;
  19. public List<AudioClip> loadedAudioClips = new List<AudioClip>();
  20.  
  21. void Start()
  22. {
  23. streamingAssetPathsToLoad = Directory.GetFiles(sourceFolder, "*", SearchOption.AllDirectories)
  24. .Where(f => Manager.IsSupportedFormat(f))
  25. .Select(f => f.Substring(rootFolder.Length + 1))
  26. .ToList();
  27. }
  28.  
  29. Coroutine lastCoroutine;
  30. private void Update()
  31. {
  32. if (streamingAssetPathsToLoad.Count > 0 && lastCoroutine == null)
  33. {
  34. var path = streamingAssetPathsToLoad[0];
  35. streamingAssetPathsToLoad.RemoveAt(0);
  36. lastCoroutine = StartCoroutine(StartLoading(path));
  37. }
  38. }
  39.  
  40.  
  41. IEnumerator StartLoading(string path)
  42. {
  43. var url = "file://" + Path.Combine(rootFolder, path);
  44. byte[] bytes = null;
  45. using (var webRequest = UnityEngine.Networking.UnityWebRequest.Get(url))
  46. {
  47. webRequest.SendWebRequest();
  48.  
  49. while (!webRequest.isDone)
  50. {
  51. yield return new WaitForEndOfFrame();
  52. }
  53.  
  54. if (webRequest.isNetworkError)
  55. {
  56. // failed
  57. lastCoroutine = null;
  58. yield break;
  59. }
  60.  
  61. bytes = webRequest.downloadHandler.data;
  62. }
  63.  
  64. var config = new AudioLoaderConfig();
  65. config.DataStream = new MemoryStream(bytes);
  66. config.UnityAudioClipName = path;
  67.  
  68. var audioLoader = new AudioLoader(config);
  69. audioLoader.StartLoading();
  70.  
  71. while (audioLoader.LoadState == AudioDataLoadState.Loading)
  72. {
  73. yield return new WaitForEndOfFrame();
  74. }
  75.  
  76. if (audioLoader.LoadState == AudioDataLoadState.Failed)
  77. {
  78. // failed
  79. lastCoroutine = null;
  80. yield break;
  81. }
  82.  
  83. loadedAudioClips.Add(audioLoader.AudioClip);
  84.  
  85. lastCoroutine = null;
  86. }
  87. }
  88. }
Advertisement
Add Comment
Please, Sign In to add comment