2016-03-07 163 views
0

我想通过屏幕上的按钮增加和减少音量。我这里的代码:减少和增加浮动增量android

//variables 
float leftVolume = 0.5f; 
float rightVolume = 0.5f; 

public void lowerVolume(View view) 
{ float decrement = 0.2f; 
    rightVolume -= decrement; 
    leftVolume -= decrement; 
    Log.d("Values","This is the value of volume"+ leftVolume); 
} 

public void raiseVolume(View view) 
{ float increment = 0.2f; 
    rightVolume = ++increment; 
    leftVolume = ++increment; 
    Log.d("Values","This is the value of volume"+ rightVolume); 
} 

的日志中显示了一些疯狂的值,如母鸡我点击rasieVolume,它进入1.2F并在那里停留。

回答

1

发生这种情况,因为你是浮动值在每次调用raiseVolume()时间设定为1.2。

public void raiseVolume(View view) 
{ float increment = 0.2f; //you set increment here 
    rightVolume = ++increment; //then simply increase it by 1 
    leftVolume = ++increment; 

    //...and so your volume will always be 1.2 at this point 
    Log.d("Values","This is the value of volume"+ rightVolume); 
} 

解决这个问题的方法是将音量设置为所述raiseVolume()方法(你已经做)的初始值OUTSIDE,然后增加它内部的raiseVolume()方法。

像这样:

//variables 
float leftVolume = 0.5f; 
float rightVolume = 0.5f; 

public void raiseVolume(View view) 
{ float increment = 0.2f; 
    rightVolume += increment; //change this line to this 
    leftVolume += increment; //change this line to this 
    Log.d("Values","This is the value of volume"+ rightVolume); 
} 
+0

ahhh我明白现在谢谢。那么如何让它每次点击按钮时减少0.2?对不起,如果这是明显的! – hgzy

+0

从你原来的代码看,你的'lowerVolume()'方法应该按照预期工作。 'rightVolume - = decrement'语句应该正确地减少音量。很高兴提供帮助,如果您觉得它解决了您的问题,请接受我的答案! – NoChinDeluxe

0

这是因为这段代码将增加increment1.2f

rightVolume = ++increment; 

然后rightVolume1.2f,并leftVolume2.2f

rightVolume += increment; 
leftVolume += increment; 
0

每次由1是增量增量值,并将其assining向左或向右卷,使用下列内容:

所以就像你在做lowerVolume你应该改变的价值。

rightVolume += increment; 
leftVolume += increment; 
0

所有给出的答案都是在严格意义上正确的,但我只是想指出,一个典型的音量控制是登录锥形而不是线性的。这与响度的感觉有关。如果你想遵循这个模型,那么你想要乘法和除法而不是加法和减法。另外,另一方面请注意:任何数字信号处理中使用的音频音量都希望保持在0到1的范围内,其中1.0表示全输出电平,0表示静音。如果你想要这样的行为,那么你应该在raiseVolume过程中将这些值修剪为< = 1.0。

//variables 
float leftVolume = 0.5f; 
float rightVolume = 0.5f; 

public void lowerVolume(View view) 
{ 
    float decrement = 0.5f; 
    rightVolume *= decrement; 
    leftVolume *= decrement; 
} 

public void raiseVolume(View view) 
{ 
    float increment = 2.0f; 
    rightVolume *= increment; 
    leftVolume *= increment; 
}