示例#1
0
    IEnumerator ReadClip(string path)
    {
        DestroyImmediate(audioSource.clip);
        WWW www = new WWW("file://" + path);

        int startNameIndex = path.LastIndexOf("\\") + 1;
        int endNameIndex   = path.LastIndexOf(".");

        audioName.text = path.Substring(startNameIndex, endNameIndex - startNameIndex);
        string fileDir = path.Substring(0, startNameIndex);

        while (!www.isDone)
        {
            yield return(null);
        }

        if (path.Contains(".mp3"))
        {
            audioSource.clip = NAudioPlayer.FromMp3Data(www.bytes);
        }
        else
        {
            audioSource.clip = www.GetAudioClip(false);
        }

        onAudioChange.Invoke(audioSource.clip.length);
        onAudioLoaded.Invoke(audioName.text, fileDir);
        openExplorerButton.interactable = true;
    }
示例#2
0
    private IEnumerator ImportAudio()
    {
        //path = EditorUtility.OpenFilePanel("Select song", "", "mp3");
        paths = StandaloneFileBrowser.OpenFilePanel("Select Song", "", "mp3", false);
        try
        {
            path = paths[0];
        }
        catch (Exception ex)
        {
            // If no file was selected stop the application
            Quit();
        }
        string url   = "file:///" + path;
        WWW    audio = new WWW(url);



        while (!audio.isDone)
        {
            yield return(0);
        }


        testAudio   = NAudioPlayer.FromMp3Data(audio.bytes);
        source.clip = testAudio;
        source.Play();
        sampleRate = AudioSettings.outputSampleRate;

        audioReady = true;
    }
示例#3
0
    // Asks the user for an mp3 (wav will also work but isn't shown), NAudio.dll turns it into a wav, and holds it for the visualizer.
    IEnumerator Start()
    {
        DontDestroyOnLoad(this.gameObject);

        string path = EditorUtility.OpenFilePanel("Music File To Open", "", "mp3");
        string url  = "file:///" + path;

        using (WWW www = new WWW(url)){
            if (path.Length != 0 && path != null)
            {
                yield return(www);

                music = NAudioPlayer.FromMp3Data(www.bytes);
                if (music.length != 0 || music != null)
                {
                    SceneManager.LoadScene("OptionsScene");
                }
                else
                {
                    EditorUtility.DisplayDialog("Error! File failed to load.", "Please select a valid mp3 file.", "Whoops!");
                    SceneManager.LoadScene("StartScene");
                }
            }
            else
            {
                EditorUtility.DisplayDialog("Error! File failed to load.", "Please select a valid mp3 file.", "Whoops!");
                SceneManager.LoadScene("StartScene");
            }
        }
    }
示例#4
0
    IEnumerator LoadMP3File(string path)
    {
        WWW www = new WWW("file://" + path);

        //Debug.Log ("loading " + path);
        yield return(www);

        if (www.error != null)
        {
            Debug.Log(www.error);
            yield break;
        }

        AudioClip clip = NAudioPlayer.FromMp3Data(www.bytes);

        clip.LoadAudioData();

        if (clip.loadState == AudioDataLoadState.Failed)
        {
            Debug.LogError("Unable to load file: " + path);
        }
        else
        {
            //Debug.Log ("done loading " + path);
            clip.name = Path.GetFileName(path);

            loadedMusics.Add(clip);

            MasterAudio.AddSongToPlaylist("Loaded Musics", clip);
        }

        loadingMusicsList.Remove(path);
    }
示例#5
0
    // a method to play a preview of the currently hovered-over track
    private IEnumerator PreviewTrack(string musicPath)
    {
        Debug.Log("Starting preview for " + musicPath);
        string _url = string.Format("file://{0}", musicPath);
        //UnityWebRequest _unityWebRequest = new UnityWebRequest(_url);

        //while (!_unityWebRequest.isDone)
        //{
        //    yield return null;
        //}

        //_unityWebRequest = UnityWebRequestMultimedia.GetAudioClip(_url, AudioType.MPEG);
        //audioSource.clip = DownloadHandlerAudioClip.GetContent(_unityWebRequest);

        WWW _www = new WWW(_url);

        while (!_www.isDone)
        {
            yield return(null);
        }

        AudioClip _clip = NAudioPlayer.FromMp3Data(_www.bytes);

        audioSource.clip = _clip;

        Debug.Log("Loaded.");

        audioSource.Play();
        audioSource.time = audioStartTime;

        currentSongPath = musicPath;

        // audioSource.volume = 0;
    }
示例#6
0
    // loads and plays song
    private IEnumerator LoadTrack(string path, SongParser.Metadata _metadata)
    {
        Debug.Log(path);
        string _url = string.Format("file://{0}", path);
        //UnityWebRequest _unityWebRequest = new UnityWebRequest(_url);

        //while (!_unityWebRequest.isDone)
        //{
        //    yield return null;
        //}

        //_unityWebRequest = UnityWebRequestMultimedia.GetAudioClip(_url, AudioType.MPEG);
        //audioSource.clip = DownloadHandlerAudioClip.GetContent(_unityWebRequest);

        WWW _www = new WWW(_url);

        while (!_www.isDone)
        {
            yield return(null);
        }

        AudioClip _clip = NAudioPlayer.FromMp3Data(_www.bytes);

        audioSource.clip = _clip;

        Debug.Log("Loaded.");

        songLoaded = true;

        audioSource.Play();

        GameObject _controller = GameObject.FindGameObjectWithTag("GameController");

        _controller.GetComponent <NoteGenerator>().InitNotes(_metadata);
    }
示例#7
0
    AudioClip MakeAudioClip(string path)
    {
        string ext = Path.GetExtension(path);

        if (audioExtensions.Contains(ext))
        {
            try
            {
                if (ext == ".mp3")
                {
                    return(NAudioPlayer.FromMp3Data(new WWW("file:///" + path).bytes));
                }
                else
                {
                    AudioClip clip = new WWW("file:///" + path).GetAudioClip();
                    while (clip.loadState != AudioDataLoadState.Loaded)
                    {
                    }
                    return(clip);
                }
            }
            catch (Exception ex)
            {
                Log("Failed to load sound sound file {0} due to Exception: {1}\nStack Trace {2}", path, ex.Source, ex.StackTrace);
            }
        }
        return(null);
    }
示例#8
0
    IEnumerator Start()
    {
#if UNITY_EDITOR
        var reqest = UnityWebRequest.Get("file://" + Application.dataPath + "/music.mp3");
        Debug.Log("Directory is : " + "file://" + Application.dataPath + "/music.mp3");
#else
        var reqest = UnityWebRequest.Get("file://" + Application.dataPath + "/../music.mp3");
        Debug.Log("Directory is : " + "file://" + Application.dataPath + "/../music.mp3");
#endif

        yield return(reqest.SendWebRequest());

        while (reqest.downloadProgress < 1.0)
        {
            yield return(null);
        }


        if (reqest.isNetworkError)
        {
            Debug.Log(reqest.error);
        }
        else
        {
            GetComponent <AudioSource>().clip = NAudioPlayer.FromMp3Data(reqest.downloadHandler.data);
        }
        GetComponent <AudioSource>().Play();
    }
示例#9
0
    private static void LoadAudio_Tool(object obj)
    {
        string path = obj as string;

        AudioClip clip;

        //FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
        //fileStream.Seek(0, SeekOrigin.Begin);
        //创建文件长度缓冲区
        //byte[] bytes = new byte[fileStream.Length];
        byte[] bytes = File.ReadAllBytes(path);
        //读取文件
        //fileStream.Read(bytes, 0, (int)fileStream.Length);
        //释放文件读取流
        //fileStream.Close();
        //fileStream.Dispose();
        //fileStream = null;
        if (bytes.Length != 0)
        {
            //WWW www = new WWW(musicfilepath);
            clip = NAudioPlayer.FromMp3Data(bytes);
        }
        else
        {
            clip = null;
        }
    }
示例#10
0
    private IEnumerator LoadAsset(FileInfo playerFile, Action <AudioClip> callback)
    {
        string    uri     = "file://" + playerFile.FullName.ToString();
        AudioType type    = playerFile.Extension == ".mp3" ? AudioType.MPEG : AudioType.WAV;
        var       request = UnityWebRequestMultimedia.GetAudioClip(uri, type);

        yield return(request.SendWebRequest());

        if (request.isNetworkError || request.isHttpError)
        {
            Debug.Log(request.error);
        }
        else
        {
            AudioClip clip;
            if (type == AudioType.MPEG)
            {
                clip = NAudioPlayer.FromMp3Data(request.downloadHandler.data);
            }
            else
            {
                clip = DownloadHandlerAudioClip.GetContent(request);
            }
            clip.name = Path.GetFileNameWithoutExtension(playerFile.FullName);
            callback(clip);
        }
    }
示例#11
0
    IEnumerator LoadAudioFromAsset(FileInfo playerFile)
    {
        if (playerFile.Name.Contains("meta"))
        {
            yield return("");
        }
        else
        {
            print(playerFile.FullName.ToString());
            string wwwPlayerFilePath = "file://" + playerFile.FullName.ToString();
            WWW    www = new WWW(wwwPlayerFilePath);
            yield return(www);

            if (playerFile.Name.Contains(".wav"))
            {
                _DestiantionAudio.clip = www.GetAudioClip(true, true);
            }
            if (playerFile.Name.Contains(".mp3"))
            {
                _DestiantionAudio.clip = NAudioPlayer.FromMp3Data(www.bytes); //www.GetAudioClip();
            }
            _DestiantionAudio.clip.name = playerFile.Name;
            _DestiantionAudio.Play();
        }
    }
示例#12
0
文件: ToGameValue.cs 项目: JCxYIS/nou
    static AudioClip LoadBGM(string path)
    {
        string type = Path.GetExtension(path).Replace(".", "");

        Debug.Log("[Audio] path=" + path + " | type=" + type);
        AudioClip       myClip = null;
        UnityWebRequest www    = null;

        byte[] byteArray;
        try
        {
            switch (type.ToLower())
            {
            case "ogg":
                    #if UNITY_STANDALONE || UNITY_EDITOR
                www = UnityWebRequestMultimedia.GetAudioClip(path, AudioType.OGGVORBIS);
                www.SendWebRequest();
                while (!www.isDone)
                {
                }
                myClip = DownloadHandlerAudioClip.GetContent(www);
                    #else
                byteArray = File.ReadAllBytes(path);
                myClip    = WAV.FromOggData(byteArray);
                    #endif
                break;

            case "mp3":
                    #if UNITY_STANDALONE || UNITY_EDITOR
                byteArray = File.ReadAllBytes(path);
                myClip    = NAudioPlayer.FromMp3Data(byteArray);
                    #else
                www = UnityWebRequestMultimedia.GetAudioClip("file://" + path, AudioType.MPEG);
                www.SendWebRequest();
                while (!www.isDone)
                {
                }
                myClip = DownloadHandlerAudioClip.GetContent(www);
                    #endif
                break;

            case "wav":
                byteArray = File.ReadAllBytes(path);
                myClip    = WAV.FromWavData(byteArray);
                break;

            default:
                Debug.LogError("Unexpected audio type");
                return(null);
            }
            Debug.Log("[Audio] Audio Length: " + myClip.length);
            return(myClip);
        }
        catch (System.Exception e)
        {
            Debug.LogError("[Audio]錯誤!" + e);
            return(null);
        }
    }
示例#13
0
 public IEnumerator testThing(WWW testWWW)
 {
     this.gameObject.AddComponent <AudioSource>();
     while (!testWWW.isDone)
     {
         yield return(0);
     }
     this.gameObject.GetComponent <AudioSource>().clip = NAudioPlayer.FromMp3Data(testWWW.bytes);
     Debug.Log("done");
 }
    //From https://gamedev.stackexchange.com/questions/112699/play-soundcloud-in-unity-3d
    /// <summary>
    /// Experimental soundcloud playback, currently waiting for api access
    /// </summary>
    /// <returns></returns>
    IEnumerator playSoundcloud()
    {
        WWW www = new WWW(soundcloudLink);

        while (!www.isDone)
        {
            yield return(0);
        }
        audioSource.clip = NAudioPlayer.FromMp3Data(www.bytes);
        //audioSource.clip = www.GetAudioClip(false, true);
    }
示例#15
0
    /// <summary>
    /// Loads and converts music file to the proper format.
    /// </summary>
    /// <param name="path">Path to the music file.</param>
    /// <returns>Converted music file.</returns>
    private AudioClip LoadMusic(string path)
    {
        string _url = string.Format("file://{0}", path);

        WWW _www = new WWW(_url);

        AudioClip _musicClip = NAudioPlayer.FromMp3Data(_www.bytes);

        _musicClip.name = Path.GetFileName(path);
        return(_musicClip);
    }
示例#16
0
    private void AsyncLoadAudio(string path)
    {
        byte[]    bytes     = File.ReadAllBytes(path);
        AudioClip monoaudio = NAudioPlayer.FromMp3Data(bytes);


        LoadAudio(monoaudio);


        Reset();
    }
    public static IEnumerator DesignateMusicFolder(Action onConvertClip)
    {
        string path = EditorUtility.OpenFolderPanel("Designate music folder", "", "");

        string[] files = Directory.GetFiles(path);

        DirectoryInfo dirInfo = new DirectoryInfo(path);

        FileInfo[] fileInfos = dirInfo.GetFiles();

        foreach (string fileName in files)
        {
            if (fileName.EndsWith(".mp3") || fileName.EndsWith(".wav"))
            {
                Debug.Log("Path string is : " + fileName);
                AudioClip convertedClip = null;


                // If the file is an mp3, we first convert it to a wav.
                if (fileName.EndsWith(".mp3"))
                {
                    WWW www = new WWW(fileName);
                    while (!www.isDone)
                    {
                        yield return(0);
                    }

                    convertedClip = NAudioPlayer.FromMp3Data(fileName);
                }

                if (fileName.EndsWith(".wav"))
                {
                    WAV wav = new WAV(fileName);

                    convertedClip = AudioClip.Create("testSound", wav.SampleCount, 1, wav.Frequency, false);
                    convertedClip.SetData(wav.LeftChannel, 0);
                }

                if (convertedClip != null && !SongManager.instance.HasSong(convertedClip))
                {
                    AddSongToGlobalManager(convertedClip);
                }
            }
        }

        if (onConvertClip != null)
        {
            onConvertClip();
        }

        yield return(null);

        //SongChoiceMenu.instance.SpawnCassettesFromSongs();
    }
示例#18
0
    IEnumerator LoadSongCoroutine(string path)
    {
        string url = string.Format("file://{0}", path);
        WWW    www = new WWW(url);

        while (!www.isDone)
        {
            yield return(null);
        }

        Music.clip = NAudioPlayer.FromMp3Data(www.bytes);
    }
示例#19
0
    public IEnumerator PlayMP3(string path)
    {
        /* Play *.mp3 audio files */
        path = "file://" + path;
        WWW www = new WWW(path);

        yield return(www);

        clip     = NAudioPlayer.FromMp3Data(www.bytes);
        src.clip = clip;
        src.Play();
    }
示例#20
0
    private IEnumerator _RequestAudioByWebRequestInPC(string path)
    {
        using (var audio_clip_request = UnityWebRequest.Get(path)) {
            yield return(audio_clip_request.SendWebRequest());

            if (audio_clip_request.isNetworkError || audio_clip_request.isHttpError)
            {
                Debug.LogError(audio_clip_request.error);
                yield break;
            }

            _audioSource.clip = NAudioPlayer.FromMp3Data(audio_clip_request.downloadHandler.data);
        }
    }
示例#21
0
    public IEnumerator LoadAudio()
    {
        loadedClips.Clear();
        WWW www = new WWW(url);

        Debug.Log(Path.GetFileName(url));
        Debug.Log(Path.GetFullPath(url));

        yield return(www);

        Debug.Log(url);
        Debug.Log(www.Current);
        Debug.Log(www.progress);
        loadedClips.Add(NAudioPlayer.FromMp3Data(www.bytes));
    }
 IEnumerator ShowLoadDialogCoroutine()
 {
     
     yield return FileBrowser.WaitForLoadDialog(false, null, "Select Sound", "Select");
 
     pathText.text = FileBrowser.Result;
 
     if (FileBrowser.Success)
     {
         byte[] SoundFile = FileBrowserHelpers.ReadBytesFromFile(FileBrowser.Result);
         yield return SoundFile;
 
         audioSource.clip = NAudioPlayer.FromMp3Data(SoundFile);
         audioSource.Play();   
     }
 }
    private static void ReadAndLoadMusicFolder(object obj)
    {
        //deprecated
        MusicFolder mf = obj as MusicFolder;

        Debug.Log("Start loading " + mf.Name);
        AudioClip clip;

        foreach (MusicData md in mf.musicdata)
        {
            //string musicfilepath = cLocalPath + md.music;
            FileStream fileStream = new FileStream(md.music, FileMode.Open, FileAccess.Read);
            fileStream.Seek(0, SeekOrigin.Begin);
            //创建文件长度缓冲区
            byte[] bytes = new byte[fileStream.Length];
            //读取文件
            fileStream.Read(bytes, 0, (int)fileStream.Length);
            //释放文件读取流
            fileStream.Close();
            fileStream.Dispose();
            fileStream = null;
            if (bytes.Length != 0)
            {
                //WWW www = new WWW(musicfilepath);
                clip = NAudioPlayer.FromMp3Data(bytes);
            }
            else
            {
                clip = null;
            }
            Debug.Log("Load " + md.music);
            //Read musicbytes Here:
            //TODO:

            //Convert Music to AudioClip Can only be deployed in the main thread.
            //So audioWavDic act as buffer

            lock (audioWavDic_lock)
            {
                audioDic.Add(md.title, clip);
                //audioWavDic.Add(md.title, musicbytes);
                Debug.Log("Add Music:" + md.title);
            }
        }
        return;
    }
示例#24
0
    private void Start()
    {
        CreateDirectories();
        trackList     = Directory.GetFiles(defaultPath + musicPath, "*.mp3");
        convertedList = new string[trackList.Length];

        for (int i = 0; i < trackList.Length; i++)
        {
            StartCoroutine(DownloadWWW("file:///" + trackList[i]));

            AudioClip clip     = NAudioPlayer.FromMp3Data(www.bytes, trackList[i]);
            string    fileName = Path.GetFileNameWithoutExtension(trackList[i]);
            convertedList[i] = SaveWav.SaveToPath(fileName, defaultPath + convertedPath, clip);
        }

        SetClip();
    }
    public IEnumerator playSampleAudio()
    {
        string path         = metaList[songIndex].musicPath;
        float  timeStart    = metaList[songIndex].sampleStart;
        float  timeDuration = metaList[songIndex].sampleLength;
        int    playingIndex = songIndex;
        WWW    www          = new WWW("file://" + path.Replace("\\", "/"));

        yield return(www);

        _nowPlaying.clip = (path.LastIndexOf(".mp3") != -1) ? NAudioPlayer.FromMp3Data(www.bytes) : www.GetAudioClip(false);
        while (playingIndex == songIndex)
        {
            _nowPlaying.volume = 1;
            _nowPlaying.time   = timeStart;
            _nowPlaying.Play();
            while (_nowPlaying.time < (timeStart + timeDuration - 1))
            {
                yield return(new WaitForSeconds(0.01f));

                if (playingIndex != songIndex)
                {
                    break;
                }
            }
            float t = _nowPlaying.volume;
            while (t > 0.0f)
            {
                if (playingIndex != songIndex)
                {
                    break;
                }
                t -= 0.01f;
                _nowPlaying.volume = t;
                yield return(new WaitForSeconds(0.01f));
            }
            if (playingIndex != songIndex)
            {
                break;
            }
            _nowPlaying.Stop();
        }
    }
示例#26
0
    IEnumerator LoadAudioClipAsync(CustomMusicUIItem item, string fileName)
    {
        string wwwPath = Path.Combine("file:///" + Application.streamingAssetsPath, fileName);

        using (var loader = new WWW(wwwPath))
        {
            yield return(loader);

            if (!string.IsNullOrEmpty(loader.error))
            {
                // Error
                Debug.LogError("Load Streaming Assets Error: " + loader.error);
                yield break;
            }

            item.clip      = NAudioPlayer.FromMp3Data(loader.bytes);
            item.clip.name = fileName;
        }
    }
示例#27
0
 private IEnumerator StartSong(string filePath)
 {
     www = new WWW(filePath);
     if (www.error != null)
     {
         Debug.Log("WWW ERR");
         Debug.Log(www.error);
     }
     else
     {
         while (!www.isDone)
         {
             Debug.Log("progress = " + www.progress);
             yield return(new WaitForSeconds(0.5f));
         }
         Debug.Log("progress = " + www.progress);
         audio.clip = NAudioPlayer.FromMp3Data(www.bytes);
         audio.Play();
     }
 }
示例#28
0
    IEnumerator ShowLoadDialogCoroutine()
    {
        yield return(FileBrowser.WaitForLoadDialog(false, null, "Load MP3", "Select"));

        path = FileBrowser.Result;

        if (FileBrowser.Success)
        {
            byte[] audioFile = FileBrowserHelpers.ReadBytesFromFile(path);
            musicFileName    = FileBrowserHelpers.GetFilename(path);
            audioSource.clip = NAudioPlayer.FromMp3Data(audioFile);
            fullLength       = (int)audioSource.clip.length;

            canJump          = true;
            audioSource.time = 0;
            AudioProfile(audioProfileVal);
        }

        varUI.GetComponent <UIControl>().enabled           = true;
        varMainCam.GetComponent <ExtendedFlycam>().enabled = true;
    }
        public IEnumerator LoadAudioCilp(string filepath)
        {
            var popup = PopupLoading.Creat();

            yield return(new WaitForEndOfFrame());

            WWW www = new WWW(ConfigUtility.fileLoadPath(filepath));

            yield return(www);

            Destroy(popup);
            yield return(new WaitForEndOfFrame());

            try {
                if (Path.GetExtension(filepath).ToLower() == ".mp3" && Application.platform != RuntimePlatform.Android)
                {
                    var clip = NAudioPlayer.FromMp3Data(www.bytes);
                    clip.name = Path.GetFileNameWithoutExtension(filepath);
                    editor.audioPlayer.SetClip(clip);
                }
                else if (Path.GetExtension(filepath).ToLower() == ".wav" ||
                         (Path.GetExtension(filepath).ToLower() == ".mp3" && Application.platform == RuntimePlatform.Android))
                {
                    var clip = www.audioClip;
                    clip.name = Path.GetFileNameWithoutExtension(filepath);
                    editor.audioPlayer.SetClip(clip);
                }
                else
                {
                    editor.debugLog.LogWarning(ExceptionList.openFileError.Value);
                    yield break;
                }
            } catch (Exception e) {
                editor.debugLog.LogWarning(ExceptionList.openFileError.Value);
                yield break;
            }
            editor.getTrackMap.header.AudioFileFullName = filepath;
            editor.debugLog.Log(MessageList.openFileSuccess.Value);
        }
示例#30
0
        IEnumerator GetAudio(int index)
        {
            musicIndex = index;
            //Music music = playlist.data[index];

            Music music = null;

            for (int i = 0; i < playlist.data.Count; i++)
            {
                if (playlist.data[i].index == musicIndex)
                {
                    //musicIndex = i;
                    music = playlist.data[i];
                    break;
                }
            }

            Debug.Log("file://" + music.path);
            WWW www = new WWW("file://" + music.path);

            yield return(www);

            if (www.error != null)
            {
                Debug.Log(www.error);
            }
            else
            {
                Message.Send <InfoMsg>(new InfoMsg(music.title + " / " + music.artist));
                //test
                audioSource.clip = NAudioPlayer.FromMp3Data(www.bytes);
                audioSource.Play();
                audioSource.time = 0;
                WindowBluetooth.GetInstance().SendBluetoothMsg(musicIndex.ToString(), SENDMSGTYPE.MUSIC, MUSICINFO.MUSIC_SELECT);
            }
        }