【问题标题】:Unity C# Add Song on runtime then play that songUnity C# 在运行时添加歌曲然后播放该歌曲
【发布时间】:2015-04-01 18:14:18
【问题描述】:

我正在尝试允许用户使用文件浏览器从统一商店添加导入歌曲。目前我正试图在菜单中播放歌曲,只是为了看看我是否正确加载了它,但似乎我无法超越这个阶段。 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;
    }           
}

}

【问题讨论】:

    标签: c# audio unity3d runtime


    【解决方案1】:

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

    尝试添加“playTrack();”在你的协程结束时,并在选择文件后使用 MonoBehaviour.StartCoroutine() 函数启动它。

    【讨论】:

    • 非常感谢!发现。是我需要的协程启动吗?
    猜你喜欢
    • 2011-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-27
    • 2013-04-03
    相关资源
    最近更新 更多