Unity2018.4.2ff 开发安卓加载外部音频文件开发说明 1、WWW方式,支持MP3和WAV音频文件格式 2、 UnityWebRequest方式,UnityWebRequestMultimedia.GetAudioClip(readPath, _audioType)不支持MP3格式,支持WAV格式; 3、WWW和UnityWebRequest都不能在安卓端使用Naudio.dll库文件创建新的wav文件。 (那位大佬如何知道方式,请在评论转告一下,谢谢!!!) 创建代码如下:
string _tempURL = _url.Replace(".mp3", ".wav");
Debug.Log("_tempURL:: " + _tempURL);
if (!File.Exists(_tempURL))
{
FileStream _fileStream = File.Open(_tempURL, FileMode.Open);
Mp3FileReader _mp3FileReader = new Mp3FileReader(_fileStream);
WaveFileWriter.CreateWaveFile(_tempURL, _mp3FileReader);
}
正确加载音频文件的代码如下所示:
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
public class LoadAudioManager : MonoSingleton<LoadAudioManager>
{
public void GetAudioClip(Transform uiRoot, string floderName)
{
for (int i = 0; i < uiRoot.childCount; i++)
{
AudioSource audioSource = uiRoot.GetChild(i).GetComponent<AudioSource>();
string audioName = uiRoot.GetChild(i).name;
StartCoroutine(LoadExternalAudioWWW(audioSource, floderName, audioName));
}
}
public IEnumerator LoadExternalAudioWWW(AudioSource audioSource, string floderName, string audioName)
{
string loadPath;
if (Application.platform == RuntimePlatform.Android)
{
loadPath = "/storage/emulated/0/ConfigFiles/Audios/" + floderName + "/" + audioName + ".mp3";
}
else
{
loadPath = Application.streamingAssetsPath + "/ConfigFiles/Audios/" + floderName + "/" + audioName + ".mp3";
}
var www = new WWW("file://" + loadPath);
yield return www;
var clip = www.GetAudioClip();
audioSource.clip = clip;
}
public IEnumerator LoadExternalAudioWebRequest(AudioSource audioSource, string floderName, string audioName, AudioType _audioType = AudioType.WAV)
{
string readPath;
if (Application.platform == RuntimePlatform.Android)
{
readPath = "file:///sdcard/ConfigFiles/Audios/" + floderName + "/" + audioName + ".wav";
Debug.LogError($"安卓端音频读取::{readPath},");
}
else
{
readPath = Application.streamingAssetsPath + "/ConfigFiles/Audios/" + floderName + "/" + audioName + ".wav";
Debug.LogError($"PC端音频读取::{readPath},");
}
yield return null;
UnityWebRequest _unityWebRequest = UnityWebRequestMultimedia.GetAudioClip(readPath, _audioType);
yield return _unityWebRequest.SendWebRequest();
if (_unityWebRequest.isHttpError || _unityWebRequest.isNetworkError)
{
Debug.Log(_unityWebRequest.error.ToString());
}
else
{
AudioClip _audioClip = DownloadHandlerAudioClip.GetContent(_unityWebRequest);
audioSource.clip = _audioClip;
}
}
}
|