c# - Unity C#在运行时添加歌曲,然后播放该歌曲

标签 c# audio unity3d runtime

我试图允许用户使用文件浏览器从统一存储中添加歌曲。目前,我正在尝试仅播放菜单中的歌曲,以查看是否正确加载了该歌曲,但似乎无法通过此阶段。 WWW功能对我来说毫无意义,我将需要有人对其进行非常简单的解释。在我看来,这应该打开文件浏览器,然后用户选择该文件,然后将所选文件加载到音频剪辑中。则调试播放按钮应该可以播放该音频剪辑,但是从暂停游戏中我可以看到文件浏览器找到了该文件并具有正确的字符串,但是从未将音频正确分配给该剪辑。我正在使用.wav和.ogg文件,因此格式没有问题。

public FileBrowser fb = new FileBrowser();
public bool toggleBrowser = true;
public string userAudio;
public AudioSource aSource;
public AudioListener aListener;
public AudioClip aClip;

void Start()
{
    if (aSource == null)
    {
        aSource = gameObject.AddComponent<AudioSource>();
        aListener = gameObject.AddComponent<AudioListener>();
    }
}

void OnGUI()
{
    // File browser, cancel returns to menu and select chooses music file to load
    if (fb.draw())
    {
        if (fb.outputFile == null)
        {
            Application.LoadLevel("_WaveRider_Menu");
        }
        else
        {
            Debug.Log("Ouput File = \"" + fb.outputFile.ToString() + "\"");
            // Taking the selected file and assigning it a string
            userAudio = fb.outputFile.ToString();


        }

    }
}

public void playTrack()
{
    //assigns the clip to the audio source and plays it
    aSource.clip = aClip;
    aSource.Play();
}

IEnumerator LoadFilePC(string filePath)
{
    filePath = userAudio;

    print("loading " + filePath);
    //Loading the string file from the File browser
    WWW www = new WWW("file:///" + filePath);

    //create audio clip from the www
    aClip = www.GetAudioClip(false);

    while (!aClip.isReadyToPlay)
    {
        yield return www;
    }           
}

}

最佳答案

有几件事可能会给您带来麻烦。
我不确定文件浏览器插件的工作原理,但是在您发布的代码中,从未调用过PlayTrack()函数,并且从未启动过LoadFilePC协程。即使您正确加载了文件,也永远不会将其分配给AudioSource或进行播放。

尝试添加“playTrack();”在协程的末尾,然后在选择文件后使用MonoBehaviour.StartCoroutine()函数启动它。

关于c# - Unity C#在运行时添加歌曲,然后播放该歌曲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29371582/

相关文章:

jar - 处理Jar文件的最小库执行

c# - C# 中的音频流式传输到 icecast2(类似于 Edcast)

java - Java 中的简单 Wav 比较

Unity3d保护代码

c# - OnTriggerEnter 触发太迟

c# - Windows Phone 7 到 iPhone 开发(我知道倒退)

c# - 如何创建一个在没有 javascript 的情况下调整页面上文本大小的函数?

c# - 插入包含字符串的变量作为新列表 C# 的参数

c# - 通过 C# 使用 ado.net 将值插入 SQL Server 数据库

c# - 如何获取Xamarin Android项目的卫星数量