【问题标题】:How to play audioclips in unity from script?如何从脚本统一播放音频剪辑?
【发布时间】:2018-07-13 01:40:42
【问题描述】:

所以我正在尝试使用 sing 方法来播放我在顶部创建的音频剪辑之一。我知道我需要一个 audioSource,我只是不知道它如何与 audioClips 相匹配。我目前没有为分配此脚本的对象分配音频源,因此这可能会影响事情。谢谢你的帮助。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Piano : MonoBehaviour {
private List<AudioClip> notes = new List<AudioClip>();

public string voice; 

public AudioClip ash1, a1, b1, csh1, c1, dsh1, d1, e1, f1, fsh1, g1, gsh1;

// Use this for initialization
void Start () {
    //octave1
    notes.Add(a1); notes.Add(b1); notes.Add(ash1); notes.Add(c1); notes.Add(csh1);notes.Add(d1); notes.Add(dsh1);
    notes.Add(e1); notes.Add(f1); notes.Add(g1); notes.Add(gsh1);

    WarmUp(voice);
}
//consider adding countertenor, true alto (i am using mezzo soprano), and baritone.
void WarmUp(string vp)
{
    //high and low end of voice parts 
    // 30 = c4 for example
    int high;
    int low;

    ArrayList range = new ArrayList();
    //c4 to c6 
    if (vp == "Soprano")
    {
        high = 0; //this is just a range to make the code shorter
        low = 7;

        for(int i = low; i < high; i++)
        {
            range.Add(notes[i]);
        }

        Sing(range);
    }
}

/**
 * @Param: range. the arraylist of range of notes. 
 * shift the pitch UP one half step if the up arrow key is pressed
 * shift the pitch down one half step if the down arrow key is pressed
 * shift the pitch up a third (4 half steps) if the left arrow key is pressed
 * shift the pitch up a fifth (7 half steps) if the right arrow key is pressed
 */
void Sing(ArrayList range)
{
    //how to play one of the audioclips in range here
}

// Update is called once per frame
void Update () {

}
}

【问题讨论】:

标签: unity3d audio-source audioclip


【解决方案1】:

如果将AudioSource 组件附加到GameObject,则可以为该组件设置AudioSource 变量,然后调用setter 函数clip(AudioClip x) 来设置源应播放的剪辑。届时,您只需拨打Play() 并等待音频剪辑的长度。

代码不应该太难弄清楚,但如果您还有其他问题,请随时提问。祝你好运!

【讨论】:

    【解决方案2】:

    AudioSource 组件附加到您的游戏对象。

    Sing:

    yourAudioSource.clip = (AudioClip)range[Random.Range(0, range.Count)];
    yourAudioSource.Play()
    

    您也可以考虑将ArrayList range 更改为List&lt;AudioClip&gt; range 或类似的东西以避免强制转换

    【讨论】:

      【解决方案3】:

      获取AudioSource _aSource 和AudioClip _aClip 的变量,并将音频源游戏对象分配给_aSource 和剪辑到inspector 上的_aClip,要播放声音的地方只需写_aSource.PlayOneShot(a_Clip) 即可。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-03-03
        • 2018-05-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多