我创建了AVAudioPlayer
,现在我想在用户点击按钮时将其静音。
我在这里尝试过:
player.volume = 1.0 //when first time i initiate my player
- (IBAction)speakerOnOff:(id)sender {
if (player.volume == 1.0) {
[player setVolume: 0.0];
NSLog(@"1volume is:%f",player.volume);
}else if (player.volume == 0.0) {
[player setVolume: 1.0];
NSLog(@"2volume is:%f",player.volume);
}
}
答案 0 :(得分:11)
if (player.volume = 1.0)
和if (player.volume = 0.0)
至少在两个级别上都是错误的。首先,C不是Pascal - =
运算符是一个赋值,可能你的意思是if (player.volume == 1.0)
。
二,即使这不是什么好事 - 比较浮点数does not do what you think it does。你最好设置一个布尔标志来指示播放器的状态(并省略else if
部分,因为它是多余的):
- (IBAction)speakerOnOff:(id)sender
{
static BOOL muted = NO;
if (muted) {
[player setVolume:1.0];
} else {
[player setVolume:0.0];
}
muted = !muted;
}
答案 1 :(得分:0)
swift 2+解决方案
let musicPlayer:AVAudioPlayer = AVAudioPlayer()
var IsMuted:Bool = false
if IsMuted == false {
IsMuted = true
musicPlayer.volume = 0
} else {
IsMuted = false
musicPlayer.volume = 1
}
- >不要忘记setCategory
到AVAudioSessionCategoryAmbient
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
try AVAudioSession.sharedInstance().setActive(true)
} catch _ {
return print("couldn't set session")
}