java 生成正弦波声音_如何生成一个正弦波声音曲线?
Why would you want to create a sine wave?
Creating a sine wave is useful for a number of things.
How hard is it?
Sine waves are about the easiest waveform to create other than square waves.
What are the steps?
There are really only three things you need to know in order to create a sine wave:
The frequency
the sample rate
the level
For our example, let’s create a 100Hz sine wave using CD quality encoding (16 bit, 44.1kHz sampling rate).
A sine wave use the Sin() function to determine the frequency. From trigonometry, we know that the period of a sine wave is 360 degrees. That is, a sine wave completes an entire revolution in 360 degrees. In radians, that’s 2 * Pi.
Sin() varies from -1 to 1. We also know that the maximum value of a 16 bit recording is 32,767 and the minimum value is -32,768.
So, basically, we simply follow a sine wave, pull out the relevant values and multiple them by our level to come up with the proper values to place in the PCM data file.
How do we determine the relevant values?
The relevant values are the ones that convert the sine wave into the time domain. If we have a sine wave that has a frequency of 80Hz, that means that 80 times a second it makes a complete (360 degree) revolution.
So, given the frequency and the sample rate, we can determine the relevant values as a series of angles. Using radians, where 360 degrees = 2 * Pi, we can do something like the following:
increment = (2* Pi) / (SampleRate / Frequency)
Increment now specifies the distance in radians that each sample is separated by. Take a look at how this works, just so it is clear.
If you divide SampleRate by Frequency, you end up with the number of samples in a specific time period. So, if the SampleRate = 44,100Hz and the frequency you want is 100Hz, then 441 samples are used to create 1 period of 100Hz musical energy. So, then you divide 2*Pi by 441 to determine the difference in the angles for each increment.
So, with this information, what do you do?
Basically, the samples are created in a loop. Amplitude is going to be your maximum amplitude (so, say 32,767 for 16 bit). You’d use the following code to get your sample:
' Loop to create the proper number of sine waves.
For sineCount = 1 To (seconds * frequency)
' Loop inside the sine wave (360 degrees)
For inputValue = 0 To (2 * Pi) Step increment
Sample = Int(amplitude * Sin(inputValue))
' Extract your data and write it to a file.
Next inputValue
Next sineCount
That’s pretty much it. Remember that when you write your data, you are going to write it as 16 bit integers. Since you are storing in 32 bit, you’ll need to extract the bytes one by one, including grabbing the sign bit.
Conclusion
This tutorial should have covered the basics of creating a sine wave signal for a PCM file.
總結
以上是生活随笔為你收集整理的java 生成正弦波声音_如何生成一个正弦波声音曲线?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python博弈论代码_使用 40 多行
- 下一篇: php fpm 测试,zabbix4.2