- Home /
Question by
larax22 · Nov 10, 2018 at 08:39 PM ·
soundsound on key
Morse - beeps not clear
Hello.
I am trying to create just a test app that would pretty much be morse translator but you also could beep your own message into it. Currently, it is set in a way that when you open the app and press space, it will beep. But there is strange... thing, sound. It is not clear. I am currently generating tone but I am thinking that I would use some mp3 of the beep instead if there will be a problem with sounds
The script is currently just attached to an empty game object.
This is totally my script and I totally did not copy and paste it and edit it just a little:
[Range(870,990)] //Creates a slider in the inspector
public float frequency1;
[Range(870,990)] //Creates a slider in the inspector
public float frequency2;
public float sampleRate = 44100;
public float waveLengthInSeconds = 2.0f;
AudioSource audioSource;
int timeIndex = 0;
void Start()
{
audioSource = gameObject.AddComponent<AudioSource>();
audioSource.playOnAwake = false;
audioSource.spatialBlend = 0; //force 2D sound
audioSource.Stop(); //avoids audiosource from starting to play automatically
}
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
timeIndex = 0; //resets timer before playing sound
audioSource.Play();
}
if(Input.GetKeyUp(KeyCode.Space))
{
audioSource.Stop();
}
}
void OnAudioFilterRead(float[] data, int channels)
{
for(int i = 0; i < data.Length; i+= channels)
{
data[i] = CreateSine(timeIndex, frequency1, sampleRate);
if(channels == 2)
data[i+1] = CreateSine(timeIndex, frequency2, sampleRate);
timeIndex++;
//if timeIndex gets too big, reset it to 0
if(timeIndex >= (sampleRate * waveLengthInSeconds))
{
timeIndex = 0;
}
}
}
//Creates a sinewave
public float CreateSine(int timeIndex, float frequency, float sampleRate)
{
return Mathf.Sin(2 * Mathf.PI * timeIndex * frequency / sampleRate);
}
Comment
Your answer
Follow this Question
Related Questions
Multiple sound sources of the same sound file 1 Answer
Getting sound trigger to work 1 Answer
Play Sound on GetKey 2 Answers