블로그 이미지
Every unexpected event is a path to learning for you. blueasa

카테고리

분류 전체보기 (2794)
Unity3D (852)
Programming (478)
Server (33)
Unreal (4)
Gamebryo (56)
Tip & Tech (185)
협업 (11)
3DS Max (3)
Game (12)
Utility (68)
Etc (98)
Link (32)
Portfolio (19)
Subject (90)
iOS,OSX (55)
Android (14)
Linux (5)
잉여 프로젝트 (2)
게임이야기 (3)
Memories (20)
Interest (38)
Thinking (38)
한글 (30)
PaperCraft (5)
Animation (408)
Wallpaper (2)
재테크 (18)
Exercise (3)
나만의 맛집 (3)
냥이 (10)
육아 (16)
Total
Today
Yesterday

Apologies for the delay, I hit a brick wall dealing with WWW - as this is my first time I use this class, I didn't know that I had to provide the FULL path to a file for it to load it successfully.

The code is taken from here, with some modifications.

Just attach this to some gameObject, and have your music files in your Asset folder (at edit-time) or the game folder (when you build).

It's in C#, if you have trouble translating to JS let me know.

  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. public class MusicPlayer : MonoBehaviour
  7. {
  8. public enum SeekDirection { Forward, Backward }
  9. public AudioSource source;
  10. public List<AudioClip> clips = new List<AudioClip>();
  11. [SerializeField] [HideInInspector] private int currentIndex = 0;
  12. private FileInfo[] soundFiles;
  13. private List<string> validExtensions = new List<string> { ".ogg", ".wav" }; // Don't forget the "." i.e. "ogg" won't work - cause Path.GetExtension(filePath) will return .ext, not just ext.
  14. private string absolutePath = "./"; // relative path to where the app is running - change this to "./music" in your case
  15. void Start()
  16. {
  17. //being able to test in unity
  18. if (Application.isEditor) absolutePath = "Assets/";
  19. if (source == null) source = gameObject.AddComponent<AudioSource>();
  20. ReloadSounds();
  21. }
  22. void OnGUI()
  23. {
  24. if (GUILayout.Button("Previous")) {
  25. Seek(SeekDirection.Backward);
  26. PlayCurrent();
  27. }
  28. if (GUILayout.Button("Play current")) {
  29. PlayCurrent();
  30. }
  31. if (GUILayout.Button("Next")) {
  32. Seek(SeekDirection.Forward);
  33. PlayCurrent();
  34. }
  35. if (GUILayout.Button("Reload")) {
  36. ReloadSounds();
  37. }
  38. }
  39. void Seek(SeekDirection d)
  40. {
  41. if (d == SeekDirection.Forward)
  42. currentIndex = (currentIndex + 1) % clips.Count;
  43. else {
  44. currentIndex--;
  45. if (currentIndex < 0) currentIndex = clips.Count - 1;
  46. }
  47. }
  48. void PlayCurrent()
  49. {
  50. source.clip = clips[currentIndex];
  51. source.Play();
  52. }
  53. void ReloadSounds()
  54. {
  55. clips.Clear();
  56. // get all valid files
  57. var info = new DirectoryInfo(absolutePath);
  58. soundFiles = info.GetFiles()
  59. .Where(f => IsValidFileType(f.Name))
  60. .ToArray();
  61. // and load them
  62. foreach (var s in soundFiles)
  63. StartCoroutine(LoadFile(s.FullName));
  64. }
  65. bool IsValidFileType(string fileName)
  66. {
  67. return validExtensions.Contains(Path.GetExtension(fileName));
  68. // Alternatively, you could go fileName.SubString(fileName.LastIndexOf('.') + 1); that way you don't need the '.' when you add your extensions
  69. }
  70. IEnumerator LoadFile(string path)
  71. {
  72. WWW www = new WWW("file://" + path);
  73. print("loading " + path);
  74. AudioClip clip = www.GetAudioClip(false);
  75. while(!clip.isReadyToPlay)
  76. yield return www;
  77. print("done loading");
  78. clip.name = Path.GetFileName(path);
  79. clips.Add(clip);
  80. }
  81. }

Couple of notes:

  1. You might ask, why use create a DirectoryInfo and then call GetFiles on that, instead of just directly go Directory.GetFiles(path)? Well, the latter one will return the paths of the files in pathrelative to path and NOT the full path (which is what you'll need to pass into WWW). i.e. if you do Directory.GetFiles("Assets"); it will return, (for example) a string array of { "Assets/soundFile1.wav", "Assets/soundFile2.ogg", etc } - these paths are relative to "Assets" while the full path would be "E:\Dropbox\UnityStuff\MyProject...\soundFile.wav"

  2. MP3s won't work in a PC build (haven't tried wav, but it should work) see this for more info. If you want MP3s, you have to go for something more complex, like MP3Sharp,NAudio and others.

  3. If you want to search recursively, change your GetFiles() call to GetFiles("*.*", SearchOption.AllDirectories)

EDIT:

JS, as per your request

  1. import UnityEngine;
  2. import System.Collections.Generic;
  3. import System.IO;
  4. import System.Linq;
  5. public enum SeekDirection { Forward, Backward }
  6. public var source : AudioSource;
  7. public var clips : List.<AudioClip> = new List.<AudioClip>();
  8. @HideInInspector @SerializeField private var currentIndex : int = 0;
  9. private var soundFiles : FileInfo[];
  10. private var validExtensions : List.<String> = new List.<String> ([ ".ogg", ".wav" ]);
  11. private var absolutePath : String = "./"; // relative path to where the app is running
  12. function Start()
  13. {
  14. //being able to test in unity
  15. if (Application.isEditor)
  16. absolutePath = "Assets/";
  17. if (source == null)
  18. source = gameObject.AddComponent.<AudioSource>();
  19. ReloadSounds();
  20. }
  21. function OnGUI()
  22. {
  23. if (GUILayout.Button("Previous")) {
  24. Seek(SeekDirection.Backward);
  25. PlayCurrent();
  26. }
  27. if (GUILayout.Button("Play current")) {
  28. PlayCurrent();
  29. }
  30. if (GUILayout.Button("Next")) {
  31. Seek(SeekDirection.Forward);
  32. PlayCurrent();
  33. }
  34. if (GUILayout.Button("Reload")) {
  35. ReloadSounds();
  36. }
  37. }
  38. function Seek(d : SeekDirection)
  39. {
  40. if (d == SeekDirection.Forward)
  41. currentIndex = (currentIndex + 1) % clips.Count;
  42. else {
  43. currentIndex--;
  44. if (currentIndex < 0) currentIndex = clips.Count - 1;
  45. }
  46. }
  47. function PlayCurrent()
  48. {
  49. source.clip = clips[currentIndex];
  50. source.Play();
  51. }
  52. function ReloadSounds()
  53. {
  54. clips.Clear();
  55. // get all valid files
  56. var info = new DirectoryInfo(absolutePath);
  57. soundFiles = info.GetFiles()
  58. .Where(function (f) { return IsValidFileType(f.Name); } )
  59. .ToArray();
  60. // and load them
  61. for(var s in soundFiles)
  62. StartCoroutine(LoadFile(s.FullName));
  63. }
  64. function IsValidFileType(fileName : String) : boolean
  65. {
  66. return validExtensions.Contains(Path.GetExtension(fileName));
  67. }
  68. function LoadFile(path : String)
  69. {
  70. var www = new WWW("file://" + path);
  71. print("loading " + path);
  72. var clip = www.GetAudioClip(false);
  73. while(!clip.isReadyToPlay)
  74. yield www;
  75. print("done loading");
  76. clip.name = Path.GetFileName(path);
  77. clips.Add(clip);
  78. }




[출처] http://answers.unity3d.com/questions/652919/music-player-get-songs-from-directory.html

반응형
Posted by blueasa
, |