unity3d - 如何从脚本统一播放音频剪辑?

标签 unity3d audio-source audioclip

因此,我尝试使用唱歌方法来播放我创建的音频片段之一。我知道我需要一个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 () {

}
}

最佳答案

AudioSource组件附加到您的GameObject。

Sing中:

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

您也可以考虑将ArrayList range更改为List<AudioClip> range或类似内容以避免强制转换

关于unity3d - 如何从脚本统一播放音频剪辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51316591/

相关文章:

c# - 如何统一循环播放音频?

c# - 在Unity3D中无法接收来自PLC的C#UDP消息,但在Wireshark中可见

android - Unity 中的屏幕录像机 Android 插件

android - setAudioRoute(int路由)的不同(int路由)值是什么?

java - 如何更改音量/更改AudioClip

c# - AudioClip 的频率和音调关系 - Unity3D

c# - Unity Android 将本地 MP3 或 WAV 加载为 AudioClip

c# - 如何使用 SteamWork.Net 获得排行榜排名?

c# - 检查是否激活多个游戏对象