Skip to main content
 首页 » 编程设计

c#之在运行时统一加载 MP3 文件

2024年02月06日13小虾米

我正在尝试使用 WWW 在运行时加载一个 mp3 文件Unity 中提供的类。

我没有收到任何错误,但是在处理完歌曲后我无法播放音乐。我到处都找遍了,找不到任何可以帮助我的东西。

这是我目前使用的代码:

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