1. Demand
- The mp3 file is placed in streamingAssets or linked in the url
- Call method: Play("mp3 name")
- Use narration background commentary: set the audio source to non-3D mode
- When the [current commentary] is interrupted to play the [next commentary], there will be a fade-out effect
Two, the code
using System;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using Cysharp.Threading.Tasks;
using System.Collections;
[RequireComponent(typeof(AudioSource))]
public class PlayAudio : MonoBehaviour
{
public AudioSource audioSource;
void Start()
{
audioSource = this.GetComponent<AudioSource>();
}
public static async UniTask LoadAudioClipAsync(string mp3file, AudioSource audioSource, float fadeDuration = 2f)
{
string url = Application.streamingAssetsPath + "/mp3/" + mp3file;
AudioClip audioClip = null;
float clipLength = 0.0f;
using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(url, AudioType.MPEG))
{
await www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.Log(www.error);
}
else
{
audioClip = DownloadHandlerAudioClip.GetContent(www);
}
}
if (audioClip != null)
{
if (audioSource.isPlaying)
{
float startVolume = audioSource.volume;
while (audioSource.volume > 0)
{
audioSource.volume -= startVolume * Time.deltaTime / fadeDuration;
await UniTask.Yield();
}
audioSource.Stop();
audioSource.volume = startVolume;
}
audioSource.clip = audioClip;
audioSource.spatialBlend = 0;
audioSource.Play();
await UniTask.Delay(TimeSpan.FromSeconds(audioSource.clip.length));
}
}
#if UNITY_EDITOR
[ContextMenu("播放声音")]
#endif
public void PlayTest()
{
audioSource = this.GetComponent<AudioSource>();
LoadAudioClipAsync("123.mp3", audioSource);
}
}