在运行时以统一方式加载MP3文件

时间:2015-06-15 18:42:22

标签: c# unity3d

我尝试使用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");
        }
    }
}

4 个答案:

答案 0 :(得分:4)

如上所述,Windows不支持MP3,因此请使用OGG或WAV。

在访问剪辑之前,您必须等待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;
}

答案 1 :(得分:1)

前提

    从Unity 2017开始不维护
  1. www类
  2. 在Unity 5.6项目中使用www打开.mp3文件后,出现错误:

      

    不支持在此平台上流式传输“ mp3”

解决方案

see my git repo

答案 2 :(得分:1)

不直接支持在Unity中的Windows中AFAIK加载mp3(2019.4.1)

使用NLayer库对我有用

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;
    }
}

source作为AudioSource

示例项目here和HTML版本here

答案 3 :(得分:0)

您可以使用AudioImporter(https://github.com/Hello-Meow/AudioImporter),并将与商业BASS库一起支持mp3(请参阅自述文件)。

它说您可以在返回第一个缓冲区后立即开始播放生成的audioClip-我现在正在测试自己。