[英]Loading MP3 files at runtime in unity
我正在嘗試使用 Unity 中提供的WWW
類在運行時加載 mp3 文件。
我沒有收到任何錯誤,但在處理歌曲后我無法播放音樂。 我到處找,找不到任何可以幫助我的東西。
這是我目前使用的代碼:
public class OpenFile : MonoBehaviour {
string path;
string extension;
public GameObject musicAnalysis;
string songName;
float length;
AudioSource song;
// Use this for initialization
void Start () {
song = musicAnalysis.GetComponent<AudioSource>();
}
// Update is called once per frame
void Update () {
if(song.isPlaying != true){
song.Play();
}
}
public void FileSelect(){
//Open windows Exploer
path = EditorUtility.OpenFilePanel("Select a Song","","");
print(path);
//Take the end of the the path and sasve it to another string
extension = path.Substring(path.IndexOf('.') + 1);
print (extension);
//Check if the user has select the correct file
if(extension == "mp3" || extension == "wav" || extension == "ogg"){
//if correct file process file
print ("You have selected the correct file type congrats");
LoadSong();
print ("Song Name: " + songName);
print ("Song Length: " + length);
}
//if the user selects the wrong file type
else{
//pop up box that tells the user that they have selected the wrong file
EditorUtility.DisplayDialog("Error","Incorrect File Type Please select another","Ok");
////Open windows Exploer
path = EditorUtility.OpenFilePanel("Select a Song","","");
}
}
void LoadSong(){
WWW www = new WWW("file://" + path);
song.clip = www.audioClip;
songName = www.audioClip.name;
length = www.audioClip.length;
while(!www.isDone){
print ("Processing File" + path);
}
if(www.isDone == true){
print ("Song has been processed");
}
}
}
如上所述,Windows 不支持 MP3,因此請使用 OGG 或 WAV。 編輯:此方法實際上適用於 mp3,我在 Unity 2019.3.6f 上使用多個文件對其進行了測試
您必須等待 WWW 完成才能訪問剪輯。 並且 WWW 必須在異步協程中加載。
public void LoadSong()
{
StartCoroutine(LoadSongCoroutine());
}
IEnumerator LoadSongCoroutine()
{
string url = string.Format("file://{0}", path);
WWW www = new WWW(url);
yield return www;
song.clip = www.GetAudioClip(false, false);
songName = song.clip.name;
length = song.clip.length;
}
不直接支持 Unity 中 Windows 中的 AFAIK 加載 mp3(2019.4.1)
IEnumerator LoadHelper(string uri)
{
UnityWebRequest www = UnityWebRequest.Get(uri);
yield return www.SendWebRequest();
if(www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
// Or retrieve results as binary data
byte[] results = www.downloadHandler.data;
var memStream = new System.IO.MemoryStream(results);
var mpgFile = new NLayer.MpegFile(memStream);
var samples = new float[mpgFile.Length];
mpgFile.ReadSamples(samples, 0, (int)mpgFile.Length);
var clip = AudioClip.Create("foo", samples.Length, mpgFile.Channels, mpgFile.SampleRate, false);
clip.SetData(samples, 0);
source.clip = clip;
}
}
作為AudioSource
source
。
您可以使用 AudioImporter ( https://github.com/Hello-Meow/AudioImporter ),並將支持與商業 BASS 庫結合使用的 mp3(請參閱自述文件)。
它說您可以在返回第一個緩沖區后立即開始播放結果音頻剪輯 - 我現在只是在測試自己。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.