【问题标题】:Unity - Can't set audio clip in C#Unity - 无法在 C# 中设置音频剪辑
【发布时间】:2019-04-25 08:00:25
【问题描述】:

编辑! 我通过将 source.play 移动到 update 中的函数来让它工作,现在我用布尔值调用它。

我目前正在 Unity 中编写 VR 鼓组编码,我需要 Unity 在从输入设备接收到 OSC 消息时播放声音。我所有的 OSC 都在工作,但是当我想播放声音时,它就完全停止了。

我有 2 个音频剪辑,我想在它们之间进行更改,我尝试过使用 2 个音频源和 1 个音频源以及多个音频剪辑,但都没有运气。 我有一个调试正在运行,它运行命令的开始,但在到达 debug.log 打印之前停止。

 if ((int)oscVal == 3)
        {
            lastTime2 = currentTime;
            DC.isActive2 = true; //It runs to this part here and then stops 
            source2.Play(); //This line doesn't seem to run
            Debug.Log("Activated Drum2"); //This line doesn't run either
        }

我希望命令运行并播放声音并继续运行。 它不这样做,只是在命令中途停止。

【问题讨论】:

  • 如果在进入下一行之前就停止了,则错误一定在前几行。您是否尝试过根据其他触发器(例如键盘)来演奏声音?
  • 我尝试将它绑定到按键,但它不会触发。我也试过让它在清醒状态下播放,效果很好,但我仍然无法播放。
  • 编辑*它与按键一起工作

标签: c# unity3d osc


【解决方案1】:

首先您需要定义 AudioSource 变量并将音频剪辑分配给它扔编辑器,您可以使用此代码

public AudioSource audioSource;
public AudioClip clip;

public void PlayMusic( bool isLoopSound) 
  { 
       audioSource.clip =clip;
       if (isLoopSound) {
            audioSource.loop = true;
        }
        else {
            audioSource.loop = false;
        } 
   }

其次,如果你想从文件路径播放音乐

 public AudioSource audioSource;

 public IEnumerator PlayMusicFromPath(string filePath, bool isLoopSound)
    {
        if (File.Exists(filePath)) {
            using (WWW www = new WWW("file://" + filePath)) {   
                yield return www;
                if(www != null) {
                    audioSource.clip = www.GetAudioClip();
                    if (isLoopSound) {
                        audioSource.loop = true;
                    }
                    else {
                        audioSource.loop = false;
                    }
                    audioSource.Play();
                    yield return null;
                }
                else {
                    Debug.Log("WWWW is null");
                    yield return null;
                }
            }
        }
        else
        {
            yield return null;
        }
    }

【讨论】:

    猜你喜欢
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多