IEnumerator GetAudioClip3() { using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(urls[2], AudioType.WAV)) { yield return(www.SendWebRequest()); if (www.isNetworkError) { Debug.Log(www.error); } else { audioClips[2] = DownloadHandlerAudioClip.GetContent(www); audioSources[2].clip = audioClips[2]; isThisDownloading.itemsDownloaded++; isThisDownloading.ChangeText(); audioSources[2].enabled = true; audioSources[2].enabled = true; } } }
// Request audio clip with url, type, progress delegate & ready delegate public static VoiceUnityRequest RequestAudioClip(string audioUrl, AudioType audioType, Action <string, float> onAudioClipProgress, Action <string, AudioClip, string> onAudioClipReady) { // Attempt to determine audio type if (audioType == AudioType.UNKNOWN) { // Determine audio type from extension string audioExt = Path.GetExtension(audioUrl).Replace(".", ""); if (!Enum.TryParse(audioExt, true, out audioType)) { onAudioClipReady?.Invoke(audioUrl, null, $"Unknown audio type\nExtension: {audioExt}"); return(null); } } // Get url string finalUrl = audioUrl; // Add file:// if needed if (!audioUrl.StartsWith("http") && !audioUrl.StartsWith("file://") && !audioUrl.StartsWith("jar:")) { finalUrl = $"file://{audioUrl}"; } // Audio clip request UnityWebRequest request = UnityWebRequestMultimedia.GetAudioClip(finalUrl, audioType); // Stream audio ((DownloadHandlerAudioClip)request.downloadHandler).streamAudio = true; // Perform request return(Request(request, (p) => onAudioClipProgress?.Invoke(audioUrl, p), (r) => { // Error #if UNITY_2020_1_OR_NEWER if (r.result != UnityWebRequest.Result.Success) #else if (r.isHttpError) #endif { onAudioClipReady?.Invoke(audioUrl, null, r.error); } // Handler else { // Get clip AudioClip clip = null; try { clip = DownloadHandlerAudioClip.GetContent(r); } catch (Exception exception) { onAudioClipReady?.Invoke(audioUrl, null, $"Failed to decode audio clip\n{exception.ToString()}"); return; } // Still missing if (clip == null) { onAudioClipReady?.Invoke(audioUrl, null, "Failed to decode audio clip"); } // Success else { clip.name = Path.GetFileNameWithoutExtension(audioUrl); onAudioClipReady?.Invoke(audioUrl, clip, string.Empty); } } })); }
IEnumerator StreamAudioFile(string filePath) { // ファイル名 string fileName = Path.GetFileName(filePath); // ファイルパスを表示 inputFieldPathName.text = filePath; // ファイル名を表示 inputFieldFileName.text = fileName; // 拡張子によってエンコード形式を設定 AudioType audioType; switch (Path.GetExtension(filePath)) { case ".wav": case ".WAV": audioType = AudioType.WAV; break; case ".ogg": case ".OGG": audioType = AudioType.OGGVORBIS; break; default: audioType = AudioType.WAV; break; } //ソース指定し音楽を開く //音楽ファイルロード using (UnityWebRequest request = UnityWebRequestMultimedia.GetAudioClip("file:///" + filePath, audioType)) { //読み込み完了まで待機 yield return(request.SendWebRequest()); if (request.isNetworkError || request.isHttpError) { Debug.Log("Error: " + request.responseCode + " : " + request.error); } else if (request.isDone) { audioSource.clip = DownloadHandlerAudioClip.GetContent(request); audioSource.clip.name = fileName; musicLength = audioSource.clip.length; timeText_length.text = string.Format("{0:00}:{1:00}", (int)(musicLength / 60), (int)(musicLength % 60)); timeSlider.maxValue = musicLength; isBegin = false; gameMng.InitNotesList(); gameMng.InitLine(); uiMng.SetMaxAreaCamPosition(gameMng.GetBarLength()); // 0秒で一時停止状態に(停止状態だと手動での再生位置変更ができないため) audioSource.Play(); audioSource.Pause(); audioSource.time = 0f; } } }
public IEnumerator Tts(string text, Action <TtsResponse> callback) { var url = "http://tsn.baidu.com/text2audio"; var param = new Dictionary <string, string>(); param.Add("tex", text); param.Add("tok", Token); param.Add("cuid", SystemInfo.deviceUniqueIdentifier); param.Add("ctp", "1"); param.Add("lan", "zh"); param.Add("spd", "5"); param.Add("pit", "5"); param.Add("vol", "10"); param.Add("per", "1"); #if UNITY_STANDALONE || UNITY_EDITOR || UNITY_UWP param.Add("aue", "6"); //设置为wav格式,移动端需要mp3格式 #endif int i = 0; foreach (var p in param) { url += i != 0 ? "&" : "?"; url += p.Key + "=" + p.Value; i++; } // 根据不同平台,获取不同类型的音频格式 #if UNITY_STANDALONE || UNITY_EDITOR || UNITY_UWP var www = UnityWebRequestMultimedia.GetAudioClip(url, AudioType.WAV); #else var www = UnityWebRequestMultimedia.GetAudioClip(url, AudioType.MPEG); #endif Debug.Log("[WitBaiduAip]" + www.url); yield return(www.SendWebRequest()); if (www.isHttpError || www.isNetworkError) { Debug.LogError(www.error); } else { var type = www.GetResponseHeader("Content-Type"); Debug.Log("[WitBaiduAip]response type: " + type); if (type.Contains("audio")) { var response = new TtsResponse { clip = DownloadHandlerAudioClip.GetContent(www) }; callback(response); } else { var textBytes = www.downloadHandler.data; var errorText = Encoding.UTF8.GetString(textBytes); Debug.LogError("[WitBaiduAip]" + errorText); callback(JsonUtility.FromJson <TtsResponse>(errorText)); } } }
/// <summary> /// Populates the sources with audio hosted on internet, non-thread blocking. /// </summary> /// <param name="fileUrl">URL of internet audio file.</param> /// <param name="variation">Variation.</param> /// <param name="successAction">Method to execute if successful.</param> /// <param name="failureAction">Method to execute if not successful.</param> // ReSharper disable RedundantNameQualifier public static IEnumerator PopulateSourceWithInternetFile(string fileUrl, SoundGroupVariation variation, System.Action successAction, System.Action failureAction) { // ReSharper restore RedundantNameQualifier if (AudioClipsByName.ContainsKey(fileUrl)) { if (successAction != null) { successAction(); } yield break; } if (InternetFilesStartedLoading.Contains(fileUrl)) // don't download the same file multiple times. { yield break; } InternetFilesStartedLoading.Add(fileUrl); AudioClip internetClip; #if UNITY_2018_3_OR_NEWER using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(fileUrl, AudioType.UNKNOWN)) { yield return(www.SendWebRequest()); if (www.isNetworkError) { if (string.IsNullOrEmpty(fileUrl)) { MasterAudio.LogWarning("Internet file is EMPTY for a Variation of Sound Group '" + variation.ParentGroup.name + "' could not be loaded."); } else { MasterAudio.LogWarning("Internet file '" + fileUrl + "' in a Variation of Sound Group '" + variation.ParentGroup.name + "' could not be loaded. This can happen if the URL is incorrect or you are not online."); } if (failureAction != null) { failureAction(); } yield break; } else { internetClip = DownloadHandlerAudioClip.GetContent(www); // assign clip name string[] urlParts = new Uri(fileUrl).Segments; internetClip.name = Path.GetFileNameWithoutExtension(urlParts[urlParts.Length - 1]); } } #else using (var fileRequest = new WWW(fileUrl)) { yield return(fileRequest); if (fileRequest.error != null) { if (string.IsNullOrEmpty(fileUrl)) { MasterAudio.LogWarning("Internet file is EMPTY for a Variation of Sound Group '" + variation.ParentGroup.name + "' could not be loaded."); } else { MasterAudio.LogWarning("Internet file '" + fileUrl + "' in a Variation of Sound Group '" + variation.ParentGroup.name + "' could not be loaded. This can happen if the URL is incorrect or you are not online."); } if (failureAction != null) { failureAction(); } yield break; } #if UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3 || UNITY_5_4 || UNITY_5_5 internetClip = fileRequest.audioClip; #else internetClip = fileRequest.GetAudioClip(); #endif // assign clip name string[] urlParts = new Uri(fileUrl).Segments; internetClip.name = Path.GetFileNameWithoutExtension(urlParts[urlParts.Length - 1]); } #endif if (!AudioResourceTargetsByName.ContainsKey(fileUrl)) { MasterAudio.LogError("No Audio Sources found to add Internet File '" + fileUrl + "' to."); if (failureAction != null) { failureAction(); } yield break; } var sources = AudioResourceTargetsByName[fileUrl]; // ReSharper disable once ForCanBeConvertedToForeach for (var i = 0; i < sources.Count; i++) { sources[i].clip = internetClip; var aVar = sources[i].GetComponent <SoundGroupVariation>(); if (aVar == null) { continue; } aVar.internetFileLoadStatus = MasterAudio.InternetFileLoadStatus.Loaded; } if (!AudioClipsByName.ContainsKey(fileUrl)) { AudioClipsByName.Add(fileUrl, internetClip); } if (successAction != null) { successAction(); } }
/// <summary> /// Load audio asset /// </summary> /// <param name="path">Path to load from</param> /// <param name="asset">AudioAsset to load into</param> /// <param name="source">Source type</param> /// <returns>True if successful</returns> public bool Load(string path, AudioAsset asset, RB.AssetSource source) { audioAsset = asset; this.path = path; if (path == null) { audioAsset.InternalSetErrorStatus(RB.AssetStatus.Failed, RB.Result.BadParam); } if (asset == null) { Debug.LogError("AudioAsset is null!"); return(false); } if (source == RB.AssetSource.Resources) { // Synchronous load if (path == null) { Debug.LogError("Audio filename is null!"); audioAsset.InternalSetErrorStatus(RB.AssetStatus.Failed, RB.Result.BadParam); return(false); } #if !RETROBLIT_STANDALONE var clip = Resources.Load <AudioClip>(path); #else var clip = Resources.LoadAudioSample(path); #endif if (clip == null) { Debug.LogError("Can't find sound file " + path + ", it must be under the Assets/Resources folder. " + "If you're trying to load from an WWW address, or Addressable Assets then please specify so with the \"source\" parameter."); audioAsset.InternalSetErrorStatus(RB.AssetStatus.Failed, RB.Result.NotFound); return(false); } // If current music clip is affected then update the clip if (asset == RetroBlitInternal.RBAPI.instance.Audio.currentMusicClip) { var channel = RetroBlitInternal.RBAPI.instance.Audio.musicChannel; if (channel.Source != null) { channel.Source.clip = clip; channel.Source.loop = true; channel.Source.Play(); } } asset.audioClip = clip; asset.progress = 1; audioAsset.InternalSetErrorStatus(RB.AssetStatus.Ready, RB.Result.Success); return(true); } else if (source == RB.AssetSource.WWW) { var audioType = AudioTypeFromPath(path); if (audioType == AudioType.UNKNOWN) { audioAsset.InternalSetErrorStatus(RB.AssetStatus.Failed, RB.Result.NotSupported); return(false); } mWebRequest = UnityWebRequestMultimedia.GetAudioClip(path, audioType); if (mWebRequest == null) { audioAsset.InternalSetErrorStatus(RB.AssetStatus.Failed, RB.Result.NoResources); return(false); } if (mWebRequest.SendWebRequest() == null) { audioAsset.InternalSetErrorStatus(RB.AssetStatus.Failed, RB.Result.NoResources); return(false); } audioAsset.progress = 0; audioAsset.InternalSetErrorStatus(RB.AssetStatus.Loading, RB.Result.Pending); return(true); } #if ADDRESSABLES_PACKAGE_AVAILABLE else if (source == RB.AssetSource.AddressableAssets) { // Exceptions on LoadAssetAsync can't actually be caught... this might work in the future so leaving it here try { mAddressableRequest = Addressables.LoadAssetAsync <AudioClip>(path); } catch (UnityEngine.AddressableAssets.InvalidKeyException e) { RBUtil.Unused(e); audioAsset.SetErrorStatus(RB.AssetStatus.Failed, RB.Result.NotFound); return(false); } catch (Exception e) { RBUtil.Unused(e); audioAsset.SetErrorStatus(RB.AssetStatus.Failed, RB.Result.Undefined); return(false); } // Check for an immediate failure if (mAddressableRequest.Status == AsyncOperationStatus.Failed) { audioAsset.addressableHandle = mAddressableRequest; audioAsset.SetErrorStatus(RB.AssetStatus.Failed, RB.Result.Undefined); return(false); } audioAsset.progress = 0; audioAsset.SetErrorStatus(RB.AssetStatus.Loading, RB.Result.Pending); return(true); } #endif else if (source == RB.AssetSource.ResourcesAsync) { // Finally attempt async resource load mResourceRequest = Resources.LoadAsync <AudioClip>(this.path); if (mResourceRequest == null) { audioAsset.InternalSetErrorStatus(RB.AssetStatus.Failed, RB.Result.NoResources); return(false); } audioAsset.InternalSetErrorStatus(RB.AssetStatus.Loading, RB.Result.Pending); } else { audioAsset.InternalSetErrorStatus(RB.AssetStatus.Failed, RB.Result.NotSupported); return(false); } return(true); }
//FixedUpdate() void FixedUpdate() { // if (!modScript.ModuleLoaded) { modScript.LoadModule(testReader); chartsLocation += modScript.ModuleFolder + "\\"; } //Starting the song if (canLoadSong && Input.GetKeyDown(KeyCode.P)) { canLoadSong = false; if (modScript.ReadChartFile(testChart)) { string[] difficulties = modScript.GetChartDifficulties(); if (modScript.ReadChartData(difficulties[1])) { //Getting the audio file string audioLoc = modScript.GetAudioFile(); string toReplace = testChart.Substring(testChart.LastIndexOf("\\") + 1); audioLoc = testChart.Replace(toReplace, audioLoc); string audioExtension = audioLoc.Substring(audioLoc.LastIndexOf(".") + 1); AudioType ext; switch (audioExtension) { case "mp3": ext = AudioType.MPEG; break; case "mp2": ext = AudioType.MPEG; break; case "ogg": ext = AudioType.OGGVORBIS; break; case "wav": ext = AudioType.WAV; break; default: throw new Exception("AUDIO TYPE NOT SUPPORTED"); } try { webAudio = UnityWebRequestMultimedia.GetAudioClip("file:///" + audioLoc, ext); webAudio.SendWebRequest(); } catch (Exception e) { throw e; } List <float>[] chartNotes = modScript.CalculateNotes(); for (int num = 0; num < chartNotes.Length; num++) { laneScripts [num].SetNotes(chartNotes [num]); } loadSongTime = Time.realtimeSinceStartup; } } } // if (Time.realtimeSinceStartup > (4f + loadSongTime) && songStartTime == 0.0f) { //Changing the song audio song.clip = DownloadHandlerAudioClip.GetContent(webAudio); //Playing the song song.Play(); // songStartTime = (float)AudioSettings.dspTime; } //Updating the measured song time if (songStartTime > 0.0) { measuredTime = (float)(AudioSettings.dspTime - songStartTime) * song.pitch; //Debug.Log("measuredTime: " + measuredTime); } //Defining the input list List <bool> inputs = new List <bool>(); foreach (LaneScript lane in laneScripts) { inputs.Add(false); } if (Input.GetKeyDown(KeyCode.S)) { debug = !debug; if (debug) { inputText.text = "Input: Keyboard\n('S' to change)"; } else { inputText.text = "Input: Touch\n('S' to change)"; } } if (debug) { if (Input.GetKey(KeyCode.D)) { inputs[0] = true; } if (Input.GetKey(KeyCode.E)) { inputs[1] = true; } if (Input.GetKey(KeyCode.W)) { inputs[2] = true; } if (Input.GetKey(KeyCode.Q)) { inputs[3] = true; } if (Input.GetKey(KeyCode.A)) { inputs[4] = true; } if (Input.GetKey(KeyCode.Z)) { inputs[5] = true; } if (Input.GetKey(KeyCode.X)) { inputs[6] = true; } if (Input.GetKey(KeyCode.C)) { inputs[7] = true; } } else { Vector3 screenPos = new Vector3(0, 0, 0); Vector3 worldPos = new Vector3(0, 0, 0); float rads = 0.0f; foreach (Touch tch in Input.touches) { screenPos.x = tch.position.x; screenPos.y = tch.position.y; worldPos = Camera.main.ScreenToWorldPoint(screenPos); rads = Mathf.Atan2(worldPos.y, worldPos.x) + (Mathf.PI / 8); //Add π/8 to offset the angle for flooring rads = (rads + 2 * Mathf.PI) % (2 * Mathf.PI); int sector = Mathf.FloorToInt(rads * (4 / Mathf.PI)); //Debug.Log("sector: " + sector); inputs[sector] = true; } } UpdateInput(inputs.ToArray(), measuredTime); }
private IEnumerator PrepareCoroutine(Song song, OnPrepared onPrepared) { Debug.Log("Loading guitar"); yield return(null); Song.Audio audio = new Song.Audio(); FileInfo guitarFileInfo = new FileInfo(song.fileInfo.Directory.FullName + "/guitar.ogg"); if (guitarFileInfo.Exists) { using (UnityWebRequest uwr = UnityWebRequestMultimedia.GetAudioClip(guitarFileInfo.FullName, AudioType.OGGVORBIS)) { yield return(uwr.SendWebRequest()); if (uwr.isNetworkError || uwr.isHttpError) { Debug.LogError(uwr.error); yield break; } yield return(null); audio.guitar = DownloadHandlerAudioClip.GetContent(uwr); } } Debug.Log("Loading song"); yield return(null); FileInfo songFileInfo = new FileInfo(song.fileInfo.Directory.FullName + "/song.ogg"); if (songFileInfo.Exists) { using (UnityWebRequest uwr = UnityWebRequestMultimedia.GetAudioClip(songFileInfo.FullName, AudioType.OGGVORBIS)) { yield return(uwr.SendWebRequest()); if (uwr.isNetworkError || uwr.isHttpError) { Debug.LogError(uwr.error); yield break; } yield return(null); audio.song = DownloadHandlerAudioClip.GetContent(uwr); } } Debug.Log("Loading rhythm"); yield return(null); FileInfo rhythmFileInfo = new FileInfo(song.fileInfo.Directory.FullName + "/rhythm.ogg"); if (rhythmFileInfo.Exists) { using (UnityWebRequest uwr = UnityWebRequestMultimedia.GetAudioClip(rhythmFileInfo.FullName, AudioType.OGGVORBIS)) { yield return(uwr.SendWebRequest()); if (uwr.isNetworkError || uwr.isHttpError) { Debug.LogError(uwr.error); yield break; } yield return(null); audio.rhythm = DownloadHandlerAudioClip.GetContent(uwr); } } song.audio = audio; Debug.Log("Audio loaded"); onPrepared(); }
public static IObservable <AudioClip> GetAudioClipAsObservable(string _url, AudioType _audioType) { return(ObservableUnity.FromCoroutine <AudioClip>((_observer, _cancellation) => FetchAudioRequest(UnityWebRequestMultimedia.GetAudioClip(_url, _audioType), _observer))); }
public AudioPreview(string url) { this.url = url; download = UnityWebRequestMultimedia.GetAudioClip(url, AudioType.WAV).SendWebRequest(); download.completed += OnWavDownloaded; }
IEnumerator LoadAudioClipCoroutine(string fullPath, bool doPlayImmediately) { fullPath = "file:///" + fullPath; // HACK for Mac? We can't find the audio file without this prefix, but *only* for loading, not saving. using (var uwr = UnityWebRequestMultimedia.GetAudioClip(fullPath, AudioType.WAV)) { ((DownloadHandlerAudioClip)uwr.downloadHandler).streamAudio = true; audioSource.clip = null; // default this to null, in case we fail. yield return(uwr.SendWebRequest()); if (uwr.isNetworkError || uwr.isHttpError) { AppDebugLog.LogError(uwr.error); yield break; } DownloadHandlerAudioClip dlHandler = (DownloadHandlerAudioClip)uwr.downloadHandler; yield return(dlHandler); if (dlHandler.isDone) { audioSource.clip = dlHandler.audioClip; if (audioSource.clip != null) { WWW download = new WWW(fullPath); // HACKED, using WWW! I think DownloadHandlerAudioClip doesn't support getting the file samples. Not sure tho. yield return(download); bool threeD = false; bool stream = false; AudioClip clip = download.GetAudioClip(threeD, stream, AudioType.WAV); //float[] samples = new float[clip.samples * clip.channels]; //clip.GetData(samples, 0); //for (int s = 0; s < 100; s++) Debug.Log(samples[s]); //AudioClip clip = DownloadHandlerAudioClip.GetContent(uwr); if (SettingsManager.Instance.DoTrimAudioClips) { clip = AudioEditor.GetQuietTrimmed(clip); } if (SettingsManager.Instance.DoNormalizeAudioClips) { clip = AudioEditor.GetNormalized(clip); } audioSource.clip = clip; GameManagers.Instance.EventManager.OnClipLoadSuccess(clip); if (doPlayImmediately) { Play(); } } else { GameManagers.Instance.EventManager.OnClipLoadFail(); Debug.Log("Couldn't load a valid AudioClip."); } } else { Debug.Log("The download process is not completely finished."); } } }
public IEnumerator carregarAudios(){ #if UNITY_ANDROID string wwwPlayerFilePath = Application.streamingAssetsPath + "/audios/" + txt_audio_pergunta + ".wav"; string wwwPlayerFilePathB = Application.streamingAssetsPath + "/audios/" + txt_audio_a0 + ".wav"; string wwwPlayerFilePathC = Application.streamingAssetsPath + "/audios/" + txt_audio_a1 + ".wav"; string wwwPlayerFilePathD = Application.streamingAssetsPath + "/audios/" + txt_audio_a2 + ".wav"; string wwwPlayerFilePathE = Application.streamingAssetsPath + "/audios/" + txt_audio_a3 + ".wav"; string wwwPlayerFilePathF = Application.streamingAssetsPath + "/audios/" + txt_audio_dica + ".wav"; #else string wwwPlayerFilePath = "file://" + Application.streamingAssetsPath + "/audios/" + txt_audio_pergunta + ".wav"; string wwwPlayerFilePathB = "file://" + Application.streamingAssetsPath + "/audios/" + txt_audio_a0 + ".wav"; string wwwPlayerFilePathC = "file://" + Application.streamingAssetsPath + "/audios/" + txt_audio_a1 + ".wav"; string wwwPlayerFilePathD = "file://" + Application.streamingAssetsPath + "/audios/" + txt_audio_a2 + ".wav"; string wwwPlayerFilePathE = "file://" + Application.streamingAssetsPath + "/audios/" + txt_audio_a3 + ".wav"; string wwwPlayerFilePathF = "file://" + Application.streamingAssetsPath + "/audios/" + txt_audio_dica + ".wav"; #endif Debug.Log(wwwPlayerFilePathF); using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(wwwPlayerFilePath, AudioType.WAV)) { yield return www.SendWebRequest(); if (www.isNetworkError) { } else { audio_pergunta.clip = DownloadHandlerAudioClip.GetContent(www); } }; using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(wwwPlayerFilePathB, AudioType.WAV)) { yield return www.SendWebRequest(); if (www.isNetworkError) { } else { audio_a0.clip = DownloadHandlerAudioClip.GetContent(www); } }; using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(wwwPlayerFilePathC, AudioType.WAV)) { yield return www.SendWebRequest(); if (www.isNetworkError) { } else { audio_a1.clip = DownloadHandlerAudioClip.GetContent(www); } }; using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(wwwPlayerFilePathD, AudioType.WAV)) { yield return www.SendWebRequest(); if (www.isNetworkError) { } else { audio_a2.clip = DownloadHandlerAudioClip.GetContent(www); } }; using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(wwwPlayerFilePathE, AudioType.WAV)) { yield return www.SendWebRequest(); if (www.isNetworkError) { } else { audio_a3.clip = DownloadHandlerAudioClip.GetContent(www); } }; using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(wwwPlayerFilePathF, AudioType.WAV)) { yield return www.SendWebRequest(); if (www.isNetworkError) { } else { audio_dica.clip = DownloadHandlerAudioClip.GetContent(www); } }; audio_pergunta.Play(); }
/// <summary> /// 音声→テキスト変換のリクエストを送信する /// </summary> /// <param name="token">アクセストークン</param> /// <returns></returns> public IEnumerator TextToSpeechRequest(string token) { Debug.Log("TextToSpeech Request"); // リクエスト中の新たなリクエストの防止 if (isRequest) { yield break; } isRequest = true; string ssml = ""; // 日本語と英語をサポート(対応したい言語があればここを修正する) if(lang.Equals("ja-JP")) { ssml = GenerateSsml(lang, "Female", "Microsoft Server Speech Text to Speech Voice (ja-JP, Ayumi, Apollo)", sentence); } else if(lang.Equals("en-US")) { ssml = GenerateSsml(lang, "Female", "Microsoft Server Speech Text to Speech Voice (en-US, ZiraRUS)", sentence); } else { Debug.LogError(lang + " language is not supported."); } byte[] postData = Encoding.UTF8.GetBytes(ssml); UnityWebRequest request = UnityWebRequestMultimedia.GetAudioClip(endpoint, AudioType.WAV); request.method = UnityWebRequest.kHttpVerbPOST; request.SetRequestHeader("Content-Type", "application/ssml+xml"); request.SetRequestHeader("X-Microsoft-OutputFormat", "riff-16khz-16bit-mono-pcm"); request.SetRequestHeader("Authorization", "Bearer " + token); request.uploadHandler = new UploadHandlerRaw(postData); yield return request.SendWebRequest(); if(request.isNetworkError) { Debug.Log(request.error); if (ErrorCallback != null) { ErrorCallback(request.error); } else { Debug.LogWarning("TextToSpeechApiErrorCallback is null."); } } else { Debug.Log("Response Code : " + request.responseCode); // レスポンスヘッダー表示 foreach (var h in request.GetResponseHeaders()) { Debug.Log(h); } if (request.responseCode == 200) { if(Callback != null) { Callback(DownloadHandlerAudioClip.GetContent(request)); } else { Debug.LogWarning("TextToSpeechApiCallback is null."); } } else { // 指定された回数だけリトライ処理を行う currentRetryCount++; if (currentRetryCount > kMaxRetryCount) { // 既にリトライ済みであればコルーチンを終了する Debug.Log("リトライ最大回数を超えました"); yield break; } // リトライ処理 Debug.LogFormat("Retry {0}回目", currentRetryCount); isRequest = false; StartCoroutine(GetTokenRequest()); yield break; } } currentRetryCount = 0; isRequest = false; }
private void PreloadClipCoroutine(string path, AudioType audioType, Dictionary <string, AudioClip> whichDict) { if (path.EndsWith(".txt")) { return; } Dbgl($"path: {path}"); path = "file:///" + path.Replace("\\", "/"); /* * try * { * AudioClip ac = WaveLoader.WaveLoader.LoadWaveToAudioClip(File.ReadAllBytes(path)); * string name = Path.GetFileNameWithoutExtension(path); * whichDict[name] = ac; * Dbgl($"Added audio clip {name} to dict"); * } * catch (Exception ex) * { * Dbgl($"Exception loading {path}\r\n{ex}"); * } */ try { var www = UnityWebRequestMultimedia.GetAudioClip(path, audioType); www.SendWebRequest(); while (!www.isDone) { } //Dbgl($"checking downloaded {filename}"); if (www != null) { //Dbgl("www not null. errors: " + www.error); DownloadHandlerAudioClip dac = ((DownloadHandlerAudioClip)www.downloadHandler); if (dac != null) { AudioClip ac = dac.audioClip; if (ac != null) { string name = Path.GetFileNameWithoutExtension(path); ac.name = name; if (!whichDict.ContainsKey(name)) { whichDict[name] = ac; } Dbgl($"Added audio clip {name} to dict"); } else { Dbgl("audio clip is null. data: " + dac.text); } } else { Dbgl("DownloadHandler is null. bytes downloaded: " + www.downloadedBytes); } } else { Dbgl("www is null " + www.url); } } catch { } }
private void _BeginDownload() { m_Data = null; var type = cRequest.assetType; var head = cRequest.head; if (CacheManager.Typeof_AudioClip.Equals(type)) { AudioType au = AudioType.MOD; if (cRequest.head is AudioType) { au = (AudioType)cRequest.head; } #if UNITY_2017 m_webrequest = UnityWebRequestMultimedia.GetAudioClip(cRequest.url, au); #else m_webrequest = UnityWebRequest.GetAudioClip(cRequest.url, au); #endif } else if (CacheManager.Typeof_AssetBundle.Equals(type)) { m_webrequest = UnityWebRequest.GetAssetBundle(cRequest.url); } else if (CacheManager.Typeof_Texture2D.Equals(type)) { #if UNITY_2017 if (cRequest.head is bool) { m_webrequest = UnityWebRequestTexture.GetTexture(cRequest.url, (bool)cRequest.head); } else { m_webrequest = UnityWebRequestTexture.GetTexture(cRequest.url); } #else if (cRequest.head is bool) { m_webrequest = UnityWebRequest.GetTexture(cRequest.url, (bool)cRequest.head); } else { m_webrequest = UnityWebRequest.GetTexture(cRequest.url); } #endif } else if (head is WWWForm) { m_webrequest = UnityWebRequest.Post(cRequest.url, (WWWForm)head); } else if (head is string) { var bytes = LuaHelper.GetBytes(head.ToString()); m_webrequest = UnityWebRequest.Put(cRequest.url, bytes); } else if (head is System.Array) { m_webrequest = UnityWebRequest.Put(cRequest.url, (byte[])head); } else { m_webrequest = UnityWebRequest.Get(cRequest.url); } if (cRequest.headers != null) { var headers = cRequest.headers; foreach (var kv in headers) { m_webrequest.SetRequestHeader(kv.Key, kv.Value); } } if (!string.IsNullOrEmpty(cRequest.overrideHost)) { m_webrequest.SetRequestHeader("host", cRequest.overrideHost); } m_asyncOperation = m_webrequest.Send(); }
private IEnumerator LoadSongCoroutine(string songName) { string path = (Application.platform == RuntimePlatform.Android) ? androidPath + songName : Application.persistentDataPath + "/" + songName; if (Application.platform == RuntimePlatform.Android) { using (UnityWebRequest song = UnityWebRequestMultimedia.GetAudioClip(path, AudioType.MPEG)) { song.url = song.url.Replace("http://localhost", "file://"); yield return(song.SendWebRequest()); if (song.isHttpError || song.isNetworkError) { Debug.LogError(song.error); } else { if (song.isDone && !_songObjectCreate) { GameObject songObject = new GameObject("Music"); songObject.AddComponent <AudioSource>(); songObject.GetComponent <AudioSource>().clip = DownloadHandlerAudioClip.GetContent(song); songObject.GetComponent <AudioSource>().Play(); _soundPlayer = songObject; System.TimeSpan time = System.TimeSpan.FromSeconds(songObject.GetComponent <AudioSource>().clip.length); _songLength.text = time.ToString("m':'ss"); _songObjectAddit = true; _songObjectCreate = true; } } } } else if (Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.WindowsEditor) { using (UnityWebRequest song = UnityWebRequestMultimedia.GetAudioClip(path, AudioType.MPEG)) { yield return(song.SendWebRequest()); if (song.isHttpError || song.isNetworkError) { Debug.LogError(song.error); } else { Debug.Log(song.url); if (song.isDone && !_songObjectCreate) { GameObject songObject = new GameObject("Music"); songObject.AddComponent <AudioSource>(); songObject.GetComponent <AudioSource>().clip = DownloadHandlerAudioClip.GetContent(song); songObject.GetComponent <AudioSource>().Play(); _soundPlayer = songObject; System.TimeSpan time = System.TimeSpan.FromSeconds(songObject.GetComponent <AudioSource>().clip.length); _songLength.text = time.ToString("m':'ss"); _songObjectAddit = true; _songObjectCreate = true; } } } } }
IEnumerator GetData() { text.text = "Loading audios..."; UnityWebRequest www = UnityWebRequest.Get(myGetAudioString); www.certificateHandler = new AcceptAllCertificates(); // To remove before going to production because certificate is valid yield return(www.SendWebRequest()); if (www.isNetworkError) { text.text = "Network error while loading"; Debug.Log(www.error); } else if (www.isHttpError) { text.text = "Http error while loading"; Debug.Log(www.error); } else { // Show results as text Debug.Log("Audios received from webservice"); Debug.Log(www.downloadHandler.text); // Deserialize result //string jsonString = JsonHelper.fixJson(www.downloadHandler.data); // byte[] is received to get images for instance string jsonString = JsonHelper.fixJson(www.downloadHandler.text); Debug.Log(jsonString); Audio[] audios = JsonHelper.FromJson <Audio>(jsonString); Debug.Log(audios.Length + " audios received"); // Display first picture if (audios.Length > 0) { text.text = audios[0].URL; using (UnityWebRequest uwr = UnityWebRequestMultimedia.GetAudioClip(audios[0].URL, UnityEngine.AudioType.WAV)) { Debug.Log("Loading the Audio as a audioCLip"); uwr.certificateHandler = new AcceptAllCertificates(); // To remove before going to production because certificate is valid yield return(uwr.SendWebRequest()); while (!uwr.isDone) { yield return(uwr); } if (uwr.isNetworkError) { text.text = "Network error while loading audioClip"; Debug.Log(uwr.error); } else if (www.isHttpError) { text.text = "Http error while loading audioClip"; Debug.Log(uwr.error); } else { // Get downloaded asset bundle Debug.Log("AudioClip loaded"); var audioC = DownloadHandlerAudioClip.GetContent(uwr); audioSrc.clip = audioC; audioSrc.Play(); //image.texture = texture; } } } } }
public IEnumerator Synthesis(string text, Action <TtsResponse> callback, int speed = 6, int pit = 5, int vol = 5, Pronouncer per = Pronouncer.Duyaya) { yield return(PreAction()); if (tokenFetchStatus == Base.TokenFetchStatus.Failed) { Debug.LogError("Token was fetched failed. Please check your APIKey and SecretKey"); callback(new TtsResponse() { err_no = -1, err_msg = "Token was fetched failed. Please check your APIKey and SecretKey" }); yield break; } var param = new Dictionary <string, string>(); param.Add("tex", text); param.Add("tok", Token); param.Add("cuid", SystemInfo.deviceUniqueIdentifier); param.Add("ctp", "1"); param.Add("lan", "zh"); param.Add("spd", Mathf.Clamp(speed, 0, 9).ToString()); param.Add("pit", Mathf.Clamp(pit, 0, 9).ToString()); param.Add("vol", Mathf.Clamp(vol, 0, 15).ToString()); param.Add("per", ((int)per).ToString()); string url = UrlTts; int i = 0; foreach (var p in param) { url += i != 0 ? "&" : "?"; url += p.Key + "=" + p.Value; i++; } #if UNITY_STANDALONE || UNITY_EDITOR || UNITY_UWP var www = UnityWebRequest.Get(url); #else var www = UnityWebRequestMultimedia.GetAudioClip(url, AudioType.MPEG); #endif yield return(www.SendWebRequest()); if (string.IsNullOrEmpty(www.error)) { var type = www.GetResponseHeader("Content-Type"); Debug.Log("response type: " + type); if (type == "audio/mp3") { #if UNITY_STANDALONE || UNITY_EDITOR || UNITY_UWP var clip = GetAudioClipFromMP3ByteArray(www.downloadHandler.data); var response = new TtsResponse { clip = clip }; #else var response = new TtsResponse { clip = DownloadHandlerAudioClip.GetContent(www) }; #endif callback(response); } else { Debug.LogError(www.downloadHandler.text); callback(JsonUtility.FromJson <TtsResponse>(www.downloadHandler.text)); } } else { Debug.LogError(www.error); } }
IEnumerator CoLoadAudioSource(string filePath, Dictionary <string, string> wavData) { UnityWebRequest www = null; foreach (KeyValuePair <string, string> p in wavData) { string url = Path.Combine(filePath, p.Value); AudioType type = AudioType.OGGVORBIS; int extensionCompareCount = 0; if (File.Exists(url)) { while (extensionCompareCount < GlobalDefine.AVAILABLE_AUDIO_EXTENSIONS.Length) { if (Path.GetExtension(url).Equals(GlobalDefine.AVAILABLE_AUDIO_EXTENSIONS[extensionCompareCount])) { break; } extensionCompareCount++; } } else { DebugWrapper.LogError($"{url} : 해당 경로가 존재하지 않습니다."); } switch (extensionCompareCount) { case 0: type = AudioType.OGGVORBIS; break; case 1: type = AudioType.WAV; break; case 2: type = AudioType.MPEG; break; } www = UnityWebRequestMultimedia.GetAudioClip( "file://" + url, type); yield return(www.SendWebRequest()); if (www.downloadHandler.data.Length != 0) { AudioClip clip = DownloadHandlerAudioClip.GetContent(www); if (clip.LoadAudioData()) { AudioClipData.Add(p.Key, clip); } } } www.Dispose(); SceneManager.LoadSceneAsync((int)eSceneName.SCENE_MAINGAME, LoadSceneMode.Single); }
IEnumerator _PollyTTS(string text, string currentLang, string currentTTSLangKey, Action <AudioClip> onDownloaded) { string clipUrl = null; var postData = new JSONObject { ["text"] = text, ["lang"] = currentLang, ["lang_code"] = currentTTSLangKey, ["company_in_editor"] = Application.companyName, ["product_in_editor"] = Application.productName, ["game_name_in_editor"] = _gameName, }; byte[] bytes = System.Text.Encoding.UTF8.GetBytes(postData.ToString()); using (var dataRequest = UnityWebRequest.Put("https://app.legendsoflearning.com/developers/tts", bytes)) { dataRequest.SetRequestHeader("Content-Type", "application/json"); dataRequest.method = UnityWebRequest.kHttpVerbPOST; yield return(dataRequest.SendWebRequest()); if (!string.IsNullOrEmpty(dataRequest.error)) { Debug.LogError($"Error: {dataRequest.error}\nGetting polly file: {text} : {currentLang}"); yield break; } var json = JSON.Parse(dataRequest.downloadHandler.text); if (!json["success"].AsBool) { Debug.LogError("Error: Success FALSE\nGetting polly file: " + text + " : " + currentLang); yield break; } clipUrl = json["file"]; } if (string.IsNullOrEmpty(clipUrl)) { Debug.LogError("Error: CLIP URL NULL\nGetting polly file: " + text + " : " + currentLang); yield break; } var clipType = clipUrl.EndsWith(".mp3") ? AudioType.MPEG : clipUrl.EndsWith(".ogg") ? AudioType.OGGVORBIS : clipUrl.EndsWith(".wav") ? AudioType.WAV : AudioType.UNKNOWN; using (var clipRequest = UnityWebRequestMultimedia.GetAudioClip(clipUrl, clipType)) { yield return(clipRequest.SendWebRequest()); if (!string.IsNullOrEmpty(clipRequest.error)) { Debug.LogError($"Error: {clipRequest.error} \nGetting polly audio clip: {text} : {currentLang}"); yield break; } onDownloaded?.Invoke(((DownloadHandlerAudioClip)clipRequest.downloadHandler).audioClip); Debug.Log("Playing polly tts: " + text); pollyTTSRequest = null; } }
private IEnumerator ChangeClip() { shouldDisableBtns = 1; if (resetAudioToDefault) { var nameWithoutExt = defaultAudioPathName.Replace(Path.GetExtension(defaultAudioPathName), ""); //Load the sound changeToClip(Resources.Load <AudioClip>(nameWithoutExt)); resetAudioToDefault = false; ProgressBar.IncrementProgressBar(0.7f); } else { AudioType audioType = AudioType.MPEG; var extension = Path.GetExtension(selectedAudioPath); if (extension == ".wav") { audioType = AudioType.WAV; } else if (extension == ".ogg") { audioType = AudioType.OGGVORBIS; } using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip("file://" + selectedAudioPath, audioType)) { yield return(www.SendWebRequest()); if (www.result == UnityWebRequest.Result.ConnectionError) { Debug.Log(www.error); } else { AudioClip myClip = DownloadHandlerAudioClip.GetContent(www); ProgressBar.IncrementProgressBar(0.3f); if (myClip == null) { Debug.Log("Clip null"); } else { changeToClip(myClip); if (audioType == AudioType.MPEG) { audioPathInUseForProcessing = StringUtil.Replace(selectedAudioPath, ".mp3", ".wav", StringComparison.OrdinalIgnoreCase); SavWav.Save(audioPathInUseForProcessing, myClip, false); } ProgressBar.IncrementProgressBar(0.7f); } } } } void changeToClip(AudioClip changeToClip) { audioSource.Stop(); audioSource.clip = changeToClip; ProgressBar.IncrementProgressBar(0.5f); audioFileChanged = false; audioClipChanged = true; } yield break; }
IEnumerator LoadMusic(string songPath) { if (WaitForFinishRoutine != null) { StopCoroutine(WaitForFinishRoutine); } Debug.Log("LoadMusic : " + songPath); if (System.IO.File.Exists(songPath)) { iOSMusicAudioSource.Stop(); Debug.Log("file://" + songPath); /* * try * { * var tfile = TagLib.File.Create(@"file://" + songPath); * string title = tfile.Tag.Title; * LastTitle = title; * Debug.Log(title); * * } * catch (Exception e) { * Debug.Log(e); * LastTitle = ""; * }; */ using (var uwr = UnityWebRequestMultimedia.GetAudioClip("file://" + songPath, AudioType.AUDIOQUEUE)) { ((DownloadHandlerAudioClip)uwr.downloadHandler).streamAudio = true; yield return(uwr.SendWebRequest()); if (uwr.result == UnityWebRequest.Result.ConnectionError || uwr.result == UnityWebRequest.Result.ProtocolError) //if (uwr.isNetworkError || uwr.isHttpError) { Debug.LogError(uwr.error); yield break; } DownloadHandlerAudioClip dlHandler = (DownloadHandlerAudioClip)uwr.downloadHandler; if (dlHandler.isDone) { AudioClip audioClip = dlHandler.audioClip; if (audioClip != null) { _audioClip = DownloadHandlerAudioClip.GetContent(uwr); // extract music data - optional //ExtractMusicData(_audioClip); iOSMusicAudioSource.clip = _audioClip; iOSMusicAudioSource.loop = false; iOSMusicAudioSource.Play(); HasAudioClipStartedPlaying = true; Debug.Log("Playing song using Audio Source!"); if (InternalMode) { WaitForFinishRoutine = StartCoroutine(WaitForFinish()); } //ResetButtonStates(); } else { Debug.Log("Couldn't find a valid AudioClip :("); } } else { Debug.Log("The download process is not completely finished."); } } } else { Debug.Log("Unable to locate converted song file."); } }
public IEnumerator Synthesis(string text, Action <TtsResponse> callback, int speed = 5, int pit = 5, int vol = 5, Pronouncer per = Pronouncer.Duxiaoyao) { yield return(PreAction()); if (tokenFetchStatus == Base.TokenFetchStatus.Failed) { Debug.LogError("Token不对"); callback(new TtsResponse() { err_no = -1, err_msg = "Token不对" }); yield break; } var param = new Dictionary <string, string>(); param.Add("tex", text); param.Add("tok", Token); param.Add("cuid", SystemInfo.deviceUniqueIdentifier); param.Add("ctp", "1"); param.Add("lan", "zh"); param.Add("spd", Mathf.Clamp(speed, 0, 9).ToString()); param.Add("pit", Mathf.Clamp(pit, 0, 9).ToString()); param.Add("vol", Mathf.Clamp(vol, 0, 15).ToString()); param.Add("per", ((int)per).ToString()); #if UNITY_STANDALONE || UNITY_EDITOR || UNITY_UWP param.Add("aue", "6"); // set to wav, default is mp3 #endif string url = UrlTts; int i = 0; foreach (var p in param) { url += i != 0 ? "&" : "?"; url += p.Key + "=" + p.Value; i++; } #if UNITY_STANDALONE || UNITY_EDITOR || UNITY_UWP var www = UnityWebRequestMultimedia.GetAudioClip(url, AudioType.WAV); #else var www = UnityWebRequestMultimedia.GetAudioClip(url, AudioType.MPEG); #endif Debug.Log("[WitBaiduAip]" + www.url); yield return(www.SendWebRequest()); if (string.IsNullOrEmpty(www.error)) { var type = www.GetResponseHeader("Content-Type"); Debug.Log("[WitBaiduAip]response type: " + type); if (type.Contains("audio")) { #if UNITY_STANDALONE || UNITY_EDITOR || UNITY_UWP var clip = DownloadHandlerAudioClip.GetContent(www); var response = new TtsResponse { clip = clip }; #else var response = new TtsResponse { clip = DownloadHandlerAudioClip.GetContent(www) }; #endif callback(response); } else { var textBytes = www.downloadHandler.data; var errorText = Encoding.UTF8.GetString(textBytes); Debug.LogError("[WitBaiduAip]" + errorText); callback(JsonUtility.FromJson <TtsResponse>(errorText)); } } else { Debug.LogError(www.error); } }
protected virtual IEnumerator playAudioFile(Model.Wrapper wrapper, string url, string outputFile, AudioType type = AudioType.WAV, bool isNative = false, bool isLocalFile = true, System.Collections.Generic.Dictionary <string, string> headers = null) { //Debug.LogWarning("playAudioFile: " + wrapper); if (wrapper != null && wrapper.Source != null) { if (!isLocalFile || (isLocalFile && new System.IO.FileInfo(outputFile).Length > 1024)) { #if UNITY_2017_1_OR_NEWER using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(url.Trim(), type)) #else using (UnityWebRequest www = UnityWebRequest.GetAudioClip(url.Trim(), type)) #endif { if (headers != null) { foreach (System.Collections.Generic.KeyValuePair <string, string> kvp in headers) { www.SetRequestHeader(kvp.Key, kvp.Value); } } #if UNITY_2017_2_OR_NEWER yield return(www.SendWebRequest()); #else yield return(www.Send()); #endif #if UNITY_2017_1_OR_NEWER if (!www.isHttpError && !www.isNetworkError) #else if (string.IsNullOrEmpty(www.error)) #endif { //just for testing! //string outputFile = Util.Config.AUDIOFILE_PATH + wrapper.Uid + extension; //System.IO.File.WriteAllBytes(outputFile, www.bytes); #if UNITY_WEBGL AudioClip ac = Util.WavMaster.ToAudioClip(www.downloadHandler.data); #else AudioClip ac = DownloadHandlerAudioClip.GetContent(www); do { yield return(ac); } while (ac.loadState == AudioDataLoadState.Loading); #endif //Debug.Log("ac.loadState: " + ac.loadState + " - " + www.downloadedBytes); if (ac.loadState == AudioDataLoadState.Loaded) { wrapper.Source.clip = ac; if (Util.Config.DEBUG) { Debug.Log("Text generated: " + wrapper.Text); } copyAudioFile(wrapper, outputFile, isLocalFile, www.downloadHandler.data); if (!isNative) { onSpeakAudioGenerationComplete(wrapper); } if ((isNative || wrapper.SpeakImmediately) && wrapper.Source != null) { wrapper.Source.Play(); onSpeakStart(wrapper); do { yield return(null); } while (!silence && Util.Helper.hasActiveClip(wrapper.Source)); if (Util.Config.DEBUG) { Debug.Log("Text spoken: " + wrapper.Text); } onSpeakComplete(wrapper); if (ac != null) { AudioClip.Destroy(ac); } } } else { string errorMessage = "Could not load the audio file the speech: " + wrapper; Debug.LogError(errorMessage); onErrorInfo(wrapper, errorMessage); } } else { string errorMessage = "Could not generate the speech: " + wrapper + System.Environment.NewLine + "WWW error: " + www.error; Debug.LogError(errorMessage); onErrorInfo(wrapper, errorMessage); } } } else { string errorMessage = "The generated audio file is invalid: " + wrapper; Debug.LogError(errorMessage); onErrorInfo(wrapper, errorMessage); } } else { string errorMessage = "'Source' is null: " + wrapper; Debug.LogError(errorMessage); onErrorInfo(wrapper, errorMessage); } }
public static IEnumerator PreloadClipCoroutine(string filename, AudioType audioType) { filename = "file:///" + filename.Replace("\\", "/"); //Dbgl($"filename: {filename}"); using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(filename, audioType)) { www.SendWebRequest(); yield return(null); //Dbgl($"checking downloaded {filename}"); if (www != null) { //Dbgl("www not null. errors: " + www.error); DownloadHandlerAudioClip dac = ((DownloadHandlerAudioClip)www.downloadHandler); if (dac != null) { AudioClip ac = dac.audioClip; if (ac != null) { string name = Path.GetFileNameWithoutExtension(filename); Dbgl($"Adding audio clip {name}"); if (name.StartsWith("music_")) { customMusic.Add(name.Substring(6), ac); } else if (name.StartsWith("ambient_")) { customAmbient.Add(name.Substring(8), ac); } else if (name.StartsWith("effect_")) { customSFX.Add(name.Substring(7), ac); } else if (name.StartsWith("list_")) { string[] vars = name.Split('_'); string key = string.Join("_", vars.Skip(2)); if (!customSFXList.ContainsKey(key)) { customSFXList[key] = new List <AudioClip>(); } customSFXList[key].Add(ac); } } else { Dbgl("audio clip is null. data: " + dac.text); } } else { Dbgl("DownloadHandler is null. bytes downloaded: " + www.downloadedBytes); } } else { Dbgl("www is null " + www.url); } } }
private IEnumerator LoadAudio(string url, string clipName) { var furl = "file:///" + url; AudioType type; switch (Path.GetExtension(url).ToLower()) { case ".mp3": type = AudioType.MPEG; break; case ".wav": type = AudioType.WAV; break; case ".ogg": type = AudioType.OGGVORBIS; break; case ".xma": type = AudioType.XMA; break; default: type = AudioType.UNKNOWN; break; } using (var www = UnityWebRequestMultimedia.GetAudioClip(furl, type)) { yield return(www.SendWebRequest()); if (www.result == UnityWebRequest.Result.ConnectionError) { Debug.Log(www.error); } else { AudioClip ac; switch (type) { case AudioType.MPEG: /* #if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN * ac = NAudioPlayer.FromMp3Data(www.downloadHandler.data); * break; #else * Debug.LogError("MP3 Playback only supported on windows at the moment. Please contact me if you know how to convert MP3 to WAV bytes universally in Unity."); #endif*/ ac = NAudioPlayer.FromMp3Data(www.downloadHandler.data); break; default: ac = DownloadHandlerAudioClip.GetContent(www); break; } ac.name = clipName; musicHandler.SongClip = ac; musicHandler.BeginGame(); } } }
// Start is called before the first frame update IEnumerator LoadAll() { string[] charDirs; string modsDir; //Identify mods and character directories if (Application.platform != RuntimePlatform.Android) { modsDir = Application.dataPath + "/../mods/"; charDirs = Directory.GetDirectories(modsDir, "CHAR_*"); if (!Directory.Exists(modsDir + "/../logs")) { Directory.CreateDirectory(modsDir + "/../logs"); } logFile = modsDir + "../logs/" + DateTime.Now.ToString("ddMMyy_HHmmss") + ".txt"; } else { if (!Permission.HasUserAuthorizedPermission(Permission.ExternalStorageWrite) && !Permission.HasUserAuthorizedPermission(Permission.ExternalStorageRead)) { // Ask for permission or proceed without the functionality enabled. Permission.RequestUserPermission(Permission.ExternalStorageRead); Permission.RequestUserPermission(Permission.ExternalStorageWrite); } if (!Directory.Exists(GetAndroidInternalFilesDir() + "/.4PUnity")) { Directory.CreateDirectory(GetAndroidInternalFilesDir() + "/.4PUnity"); File.Create(GetAndroidInternalFilesDir() + "/.4PUnity/.nomedia"); } if (!Directory.Exists(GetAndroidInternalFilesDir() + "/.4PUnity/music")) { Directory.CreateDirectory(GetAndroidInternalFilesDir() + "/.4PUnity/music"); } if (!Directory.Exists(GetAndroidInternalFilesDir() + "/.4PUnity/logs")) { Directory.CreateDirectory(GetAndroidInternalFilesDir() + "/.4PUnity/logs"); } modsDir = GetAndroidInternalFilesDir() + "/.4PUnity/"; charDirs = Directory.GetDirectories(modsDir, "CHAR_*"); logFile = modsDir + "logs/" + DateTime.Now.ToString("ddMMyy_HHmmss") + ".txt"; } //Load music List <string> musicFiles = new List <string>(Directory.GetFiles(modsDir + "music", "*.ogg")); musicFiles.AddRange(Directory.GetFiles(modsDir + "music", "*.mp3")); Dropdown mdd = GameObject.Find("MusicDropdown").GetComponent <Dropdown>(); List <string> options = new List <string>(); foreach (string track in musicFiles) { string track2 = track.Replace('\\', '/'); UnityWebRequest rq = UnityWebRequestMultimedia.GetAudioClip("file://" + track2, AudioType.OGGVORBIS); rq.SendWebRequest(); while (rq.downloadProgress < 1) { ; } yield return(rq); string trackName = track2.Substring(track2.LastIndexOf("/") + 1); trackName = trackName.Substring(0, trackName.Length - 4); music.Add(((DownloadHandlerAudioClip)rq.downloadHandler).audioClip); options.Add(trackName); } mdd.ClearOptions(); mdd.AddOptions(options); mdd.onValueChanged.AddListener((int a) => { GameObject.Find("EventSystem").GetComponent <UI>().MusicChange(a); }); GameObject cam = GameObject.Find("MainCam"); cam.GetComponent <AudioSource>().clip = music[0]; cam.GetComponent <AudioSource>().loop = true; GameObject canvas = GameObject.Find("CharContent"); DefaultControls.Resources uiResources = new DefaultControls.Resources(); var i = 0; VP vpClass = GameObject.Find("EventSystem").GetComponent <VP>(); foreach (string ch in charDirs) { string charName = ch.Replace('\\', '/').Substring(ch.LastIndexOf('_') + 1); GameObject charButton = DefaultControls.CreateButton(uiResources); charButton.name = charName; charButton.transform.SetParent(canvas.transform); canvas.GetComponent <RectTransform>().offsetMin = new Vector2(canvas.GetComponent <RectTransform>().offsetMin.x, canvas.GetComponent <RectTransform>().offsetMin.y + 200); charButton.GetComponent <RectTransform>().anchorMax = new Vector2(0.5f, 0); charButton.GetComponent <RectTransform>().anchorMin = new Vector2(0.5f, 0); charButton.GetComponent <RectTransform>().anchoredPosition = new Vector3(0, -100 - i * 200, 0); charButton.GetComponent <RectTransform>().sizeDelta = new Vector2(200, 200); Destroy(charButton.transform.GetChild(0).gameObject); Debug.Log(Directory.GetFiles(ch, charName + ".png")[0]); charButton.GetComponent <Image>().sprite = LoadNewSprite(Directory.GetFiles(ch, charName + ".png")[0]); charButton.GetComponent <Button>().onClick.AddListener(() => { vpClass.PoseSwitch(charName, vpClass.curAnim); }); charButton.GetComponent <RectTransform>().localScale = new Vector3(1, 1, 1); i++; List <string> files = new List <string>(Directory.GetFiles(ch, "*.mp4")); files.Sort(); charMods.Add(charName, files); } GameObject camera = GameObject.Find("MainCam"); bool firstVp = true; foreach (KeyValuePair <string, List <string> > charAnims in ModLoader.charMods) { List <VideoPlayer> players = new List <VideoPlayer>(); foreach (string file in charAnims.Value) { //VideoPlayer vp = camera.AddComponent<VideoPlayer>(); //vp.waitForFirstFrame = true; //vp.isLooping = true; //vp.aspectRatio = VideoAspectRatio.FitVertically; //vp.loopPointReached += vpClass.Looped; //vp.prepareCompleted += vpClass.Prepared; //vp.audioOutputMode = VideoAudioOutputMode.Direct; //vp.SetDirectAudioVolume(0, 1); //vp.url = file; //vp.Prepare(); //while (!vp.isPrepared) yield return null; //loadedMods++; //currentLoaded -= fraction; //loadingBar.offsetMax = new Vector2(-currentLoaded, 10f); //loadingText.text = loadedMods + "/" + totalMods; //players.Add(vp); if (firstVp) { firstVp = false; vpClass.curChar = charAnims.Key; vpClass.curAnim = 0; } } VP.vps.Add(charAnims.Key, players); VP.charList.Add(charAnims.Key); Debug.Log(VP.vps); } Application.logMessageReceived += LogHandler; loaded = true; }
public void DownloadClip() { dClip = UnityWebRequestMultimedia.GetAudioClip(url, AudioType.MPEG); dClip.SendWebRequest(); }
public static IEnumerator PreloadClipsCoroutine() { string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "HereFishy", "herefishy.wav"); if (!File.Exists(path)) { Dbgl($"file {path} does not exist!"); yield break; } string filename = "file:///" + path.Replace("\\", "/"); Dbgl($"getting audio clip from filename: {filename}"); using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(filename, AudioType.WAV)) { www.SendWebRequest(); yield return(null); if (www != null) { DownloadHandlerAudioClip dac = ((DownloadHandlerAudioClip)www.downloadHandler); if (dac != null) { AudioClip ac = dac.audioClip; if (ac != null) { Dbgl("audio clip is not null. samples: " + ac.samples); fishyClip = ac; } else { Dbgl("audio clip is null. data: " + dac.text); } } else { Dbgl("DownloadHandler is null. bytes downloaded: " + www.downloadedBytes); } } else { Dbgl("www is null " + www.url); } } path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "HereFishy", "wee.wav"); filename = "file:///" + path.Replace("\\", "/"); Dbgl($"filename: {filename}"); using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(filename, AudioType.WAV)) { www.SendWebRequest(); yield return(null); //Dbgl($"checking downloaded {filename}"); if (www != null) { //Dbgl("www not null. errors: " + www.error); DownloadHandlerAudioClip dac = ((DownloadHandlerAudioClip)www.downloadHandler); if (dac != null) { AudioClip ac = dac.audioClip; if (ac != null) { Dbgl("audio clip is not null. samples: " + ac.samples); weeClip = ac; } else { Dbgl("audio clip is null. data: " + dac.text); } } else { Dbgl("DownloadHandler is null. bytes downloaded: " + www.downloadedBytes); } } else { Dbgl("www is null " + www.url); } } }
public IEnumerator LoadAudio() { if (_longCutEffectsAudioClips == null) { if (Directory.Exists(audioFolder + "/longcut") && Directory.GetFiles(audioFolder + "/longcut").Length > 0) { string[] audioFiles = Directory.GetFiles(audioFolder + "/longcut"); _longCutEffectsAudioClips = new AudioClip[audioFiles.Length]; int index = 0; foreach (string filePath in audioFiles) { string file = "file:///" + filePath; UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(file, AudioType.OGGVORBIS); AudioClip audioFile = null; yield return(www.SendWebRequest()); audioFile = DownloadHandlerAudioClip.GetContent(www); if (audioFile != null || audioFile.frequency == 0) { _longCutEffectsAudioClips[index] = audioFile; Logger.log.Debug(audioFile.frequency + " | Audio loaded: " + file); index++; } else { Logger.log.Debug(audioFile.frequency + " | Audio didn't load: " + file); } } } if (_shortCutEffectsAudioClips == null) { if (Directory.Exists(audioFolder + "/shortcut") && Directory.GetFiles(audioFolder + "/shortcut").Length > 0) { string[] audioFiles = Directory.GetFiles(audioFolder + "/shortcut"); _shortCutEffectsAudioClips = new AudioClip[audioFiles.Length]; int index = 0; foreach (string filePath in audioFiles) { string file = "file:///" + filePath; UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(file, AudioType.OGGVORBIS); AudioClip audioFile = null; yield return(www.SendWebRequest()); audioFile = DownloadHandlerAudioClip.GetContent(www); if (audioFile != null || audioFile.frequency == 0) { _shortCutEffectsAudioClips[index] = audioFile; Logger.log.Debug(audioFile.frequency + " | Audio loaded: " + file); index++; } else { Logger.log.Debug(audioFile.frequency + " | Audio didn't load: " + file); } } } } if (_badCutSoundEffectAudioClips == null) { if (Directory.Exists(audioFolder + "/badcut") && Directory.GetFiles(audioFolder + "/badcut").Length > 0) { string[] audioFiles = Directory.GetFiles(audioFolder + "/badcut"); _badCutSoundEffectAudioClips = new AudioClip[audioFiles.Length]; int index = 0; foreach (string filePath in audioFiles) { string file = "file:///" + filePath; UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(file, AudioType.OGGVORBIS); AudioClip audioFile = null; yield return(www.SendWebRequest()); audioFile = DownloadHandlerAudioClip.GetContent(www); if (audioFile != null || audioFile.frequency == 0) { _badCutSoundEffectAudioClips[index] = audioFile; Logger.log.Debug(audioFile.frequency + " | Audio loaded: " + file); index++; } else { Logger.log.Debug(audioFile.frequency + " | Audio didn't load: " + file); } } } } if (_bombExplosionAudioClips == null) { if (Directory.Exists(audioFolder + "/bomb") && Directory.GetFiles(audioFolder + "/bomb").Length > 0) { string[] audioFiles = Directory.GetFiles(audioFolder + "/bomb"); _bombExplosionAudioClips = new AudioClip[audioFiles.Length]; int index = 0; foreach (string filePath in audioFiles) { string file = "file:///" + filePath; UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(file, AudioType.OGGVORBIS); AudioClip audioFile = null; yield return(www.SendWebRequest()); audioFile = DownloadHandlerAudioClip.GetContent(www); if (audioFile != null || audioFile.frequency == 0) { _bombExplosionAudioClips[index] = audioFile; Logger.log.Debug(audioFile.frequency + " | Audio loaded: " + file); index++; } else { Logger.log.Debug(audioFile.frequency + " | Audio didn't load: " + file); } } } } if (_clickSounds == null) { if (Directory.Exists(audioFolder + "/click") && Directory.GetFiles(audioFolder + "/click").Length > 0) { string[] audioFiles = Directory.GetFiles(audioFolder + "/click"); _clickSounds = new AudioClip[audioFiles.Length]; int index = 0; foreach (string filePath in audioFiles) { string file = "file:///" + filePath; UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(file, AudioType.OGGVORBIS); AudioClip audioFile = null; yield return(www.SendWebRequest()); audioFile = DownloadHandlerAudioClip.GetContent(www); if (audioFile != null || audioFile.frequency == 0) { _clickSounds[index] = audioFile; Logger.log.Debug(audioFile.frequency + " | Audio loaded: " + file); index++; } else { Logger.log.Debug(audioFile.frequency + " | Audio didn't load: " + file); } } } } } }