使用以下代码,我可以在Unity编辑器中使用UnityWebRequestMultimedia.GetAudioClip加载音频,但当我在Android上运行它时,我无法从用户的设备加载任何文件。
void Start() {
audio = GetComponent<AudioSource>();
string fullPath = Path.Combine("file://" + previewSong);
StartCoroutine(GetAudioClip(fullPath));
}
IEnumerator GetAudioClip(string fullPath)
{
using (var uwr = UnityWebRequestMultimedia.GetAudioClip(fullPath, AudioType.MPEG))
{
((DownloadHandlerAudioClip)uwr.downloadHandler).streamAudio = true;
yield return uwr.SendWebRequest();
if (uwr.isNetworkError || uwr.isHttpError)
{
debugSongPath2.text = uwr.error;
yield break;
}
DownloadHandlerAudioClip dlHandler = (DownloadHandlerAudioClip)uwr.downloadHandler;
if (dlHandler.isDone)
{
audio.clip = dlHandler.audioClip;
if (audio.clip != null)
{
audio.clip = DownloadHandlerAudioClip.GetContent(uwr);
Debug.Log("Playing song using Audio Source!");
}
else
{
Debug.Log("Couldn't find a valid AudioClip.");
}
}
else
{
Debug.Log("The download process is not completely finished.");
}
}
}
我遇到的错误因URL开头的形式而异。
Path.Combine("file:/" + previewSong);
malformed URL
Path.Combine("file://" + previewSong);
http:/1.1 404 not found
Path.Combine("file:///" + previewSong);
unknown error
Path.Combine("file:////" + previewSong);
unknown error
当我在手机上输出URL时,它们看起来是正确的。下面是一个示例路径:
file:///storage/emulated/0/Music/Deorro/Deorro - Five Hours.mp3
我以前用WWW.GetAudioClip成功地从这个URL加载音频,但这已经过时了。这让我相信URL是正确的。我尝试过使用和不使用开发模式进行构建。不知道还能尝试什么。我想用UnityWebRequestMultimedia来实现这一点,但如果有一种替代的、更有效的加载本地文件的方法,我愿意接受
问题出在新的Android 11作用域存储上,它禁用了READ_EXTERNAL_storage。我不得不将以下内容添加到我的AndroidManifest.xml中:
<manifest ... >
<!-- This attribute is "false" by default on apps targeting Android 10 or higher. -->
<application android:requestLegacyExternalStorage="true" ... >
...
</application>
</manifest>
https://developer.android.com/training/data-storage/use-cases#opt-范围外存储
更改构建设置以授予对外部sd卡的写访问权限。我正在使用以下代码从android中的指定位置获取音频。我试过你的代码,但不知怎么不起作用。
IEnumerator GetAudioClip2(string fullPath)
{
debugSongPath2.text = previewSong;
using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(fullPath, AudioType.MPEG))
{
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
AudioClip myClip = DownloadHandlerAudioClip.GetContent(www);
audioSource.clip = myClip;
audioSource.Play();
}
}
}
我的完整路径是";file:///storage/emulated/0/Samsung/Music/Over地平线.mp3";
async void GetAudioClip(string audioURL, GameObject itemMedia)
{
try
{
audioPlayer.clip = await UnityHttpClient.GetAudioClip(audioURL);
panelLoading.SetActive(false);
timeEndAudio.GetComponent<Text>().text = Helper.FormatTime(audioPlayer.clip.length);
sliderControlAudio.GetComponent<Slider>().maxValue = audioPlayer.clip.length;
btnControlAudio.interactable = true;
btnExitAudio.interactable = true;
IsPlayingAudio = true;
ControlAudio(IsPlayingAudio);
}
catch (Exception exception)
{
SetUIErrorNetwork(itemMedia);
Toast.ShowCommonToast(exception.Message, APIUrlConfig.SERVER_ERROR_RESPONSE_CODE);
}
}