如何在Unity中使用脚本播放音频片段?

3

所以我正在尝试让sing方法播放我在上面创建的音频剪辑之一。我知道我需要一个audioSource,但我不知道它如何与audioClips配合使用。目前我没有将audiosoure分配给此脚本所分配的对象,因此这可能会影响事情的进行。感谢您的帮助。

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 () {

}
}

我认为您正在寻找的是:https://docs.unity3d.com/ScriptReference/AudioSource.PlayOneShot.html 或者 https://docs.unity3d.com/ScriptReference/AudioSource.Play.html,但是正如TopRamen所说,您需要一个AudioSource。然后,只需创建一个类型为AudioSource的变量,使用GetComponent来填充该变量,然后调用variableName.PlayOneShot()或variableName.Play()即可。 - Vitor Figueredo
3个回答

3
如果您将AudioSource组件附加到GameObject,那么您可以将AudioSource变量设置为该组件,然后调用setter函数clip(AudioClip x)来设置源应播放的剪辑。此时,您只需调用Play()并等待音频剪辑的长度即可。
代码不应该太难理解,但如果您有任何问题,请随时问。祝好运!

1

将一个AudioSource组件附加到你的游戏对象上。

Sing中:

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

您可能还可以考虑将 ArrayList range 更改为 List<AudioClip> range 或类似方式以避免强制转换。


0

定义一个AudioSource类型的变量_aSource和一个AudioClip类型的变量_aClip,然后将音频源对象分配给_aSource并将音频剪辑分配给检查器上的_aClip。在想播放声音的地方,只需编写_aSource.PlayOneShot(a_Clip)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接