我正在尝试使用 iOS 创建自定义波形信号 当添加第二个for循环来创建时,它的作用是在间隔0.8T和0.9T m之间创建脉冲,其中T是周期。
当我尝试添加第三个 for 循环来创建一个时,它在 0.7T 周期后创建了一个带有凸双曲线的奇怪信号,而不是生成新的脉冲。
能否请您告诉我应该修改或重置哪个缓冲区变量以便生成多个脉冲?
下面是我的代码
// Fixed amplitude is good enough for our purposes
const double amplitude = 1.0;
// Get the tone parameters out of the view controller
ToneGeneratorViewController *viewController =
(ToneGeneratorViewController *)inRefCon;
double theta = viewController->theta;
//double theta_increment = 2.0 * M_PI * viewController->frequency / viewController->sampleRate;
double theta_increment = viewController->sampleRate / viewController->frequency;
(采样率 = 44100;,频率 = 44.44)
const int channel = 0;
Float32 *buffer = (Float32 *)ioData->mBuffers[channel].mData;
float squareIndex = 0.0;
//Generate the samples//
for (UInt32 frame = 0; frame < inNumberFrames; frame++)
{
float k =0.0;
float y = 34.0/75.0;
if( fmodf(squareIndex, theta_increment)/theta_increment < y) {
k = 1.0;
} else {
k = 0.0;
}
buffer[frame] = k * amplitude;
squareIndex += 1.0;
if(squareIndex >= theta_increment) squareIndex-=theta_increment;
viewController->theta = theta;
}
for (UInt32 frame = 0; frame < inNumberFrames; frame++)
{
float k =0.0;
float z = 0.8;
float y = 0.9;
if( z < fmodf(squareIndex, theta_increment)/theta_increment < y) {
k = 0.0;
} else {
k = 1.0;
}
buffer[frame] += k * amplitude;
squareIndex += 1.0;
if(squareIndex >= theta_increment) squareIndex-=theta_increment;
viewController->theta = theta;
}
for (UInt32 frame = 0; frame < inNumberFrames; frame++)
{
float k =0.0;
float z = 0.6;
float y = 0.7;
if( z < fmodf(squareIndex, theta_increment)/theta_increment < y) {
k = 0.0;
} else {
k = 1.0;
}
buffer[frame] += k * amplitude;
squareIndex += 1.0;
if(squareIndex >= theta_increment) squareIndex-=theta_increment;
viewController->theta = theta;
}
最佳答案
由于我们在提供的代码中没有看到缓冲区分配,我假设缓冲区有足够的大小来容纳所有样本(否则缓冲区溢出可能会导致各种未定义的行为)。
通过提供的代码,您应该意识到在循环中,表达式
if( z < fmodf(squareIndex, theta_increment)/theta_increment < y) {
从左到右计算为:
if( (z < fmodf(squareIndex, theta_increment)/theta_increment) < y) {
我们来看第二个循环来说明效果:
只要squareIndex 小于
0.8*theta_increment`,子表达式
(z < fmodf(squareIndex, theta_increment)/theta_increment)
计算为 false
,在数值提升后小于 y=0.9
,因此整体表达式为 true
(所以 k=0
).一旦 squareIndex
变得超过 0.8*theta_increment
(z < fmodf(squareIndex, theta_increment)/theta_increment)
变为 true
,在数值提升之后再次大于 y=0.9
,因此整体表达式变为 false
(因此 k=1
).
然后循环生成以下曲线:
从上到下是第一、第二和第三个循环,然后是组合波形。
要解决此问题,您可以将条件更改为:
float t = fmodf(squareIndex, theta_increment)/theta_increment;
if (z < t && t < y) {
k = 1.0;
} else {
k = 0.0;
}
然后应生成以下波形:
关于添加第三个脉冲时 iOS 生成脉冲失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23621821/