Reputation: 55
So I am trying to get the sing method to play one of the audioclips I created up top. I know I need an audioSource, I just have no clue how it fits in with the audioClips. I don't currently have an audiosoure assigned to the object that this script is assigned to, so that might impact things. Thanks for your help.
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 () {
}
}
Upvotes: 3
Views: 8749
Reputation: 3108
Attach a AudioSource
component to your GameObject.
In Sing
:
yourAudioSource.clip = (AudioClip)range[Random.Range(0, range.Count)];
yourAudioSource.Play()
You might also consider changing ArrayList range
to List<AudioClip> range
or similar to avoid the cast
Upvotes: 1
Reputation: 39
If you attach an AudioSource
component to the GameObject
, then you could set an AudioSource
variable to that component and then call the setter function clip(AudioClip x)
to set the clip the source should play. At that point, you could just call Play()
and wait for the length of the audio clip.
Code shouldn't be too difficult to figure out but if you have any more questions, don't hesitate to ask. Good luck!
Upvotes: 3
Reputation: 1
Take a variable of AudioSource _aSource and AudioClip _aClip and assign the audio source game object to the _aSource and clip to the _aClip on the inspector and where want to play the sound just write _aSource.PlayOneShot(a_Clip) that it.
Upvotes: 0