I have created AVAudioPlayer
, Now I want to mute it when user click button.
Here what I have tried :
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);
}
}
if (player.volume = 1.0)
and if (player.volume = 0.0)
are erroneous at least on two levels. First, C is not Pascal - the =
operator is an assignment, probably you meant if (player.volume == 1.0)
instead.
Two, even this wouldn't be any good - comparing floating-point numbers does not do what you think it does . You better set a Boolean flag to indicate the state of the player (and omit the else if
part since it's redundant):
- (IBAction)speakerOnOff:(id)sender
{
static BOOL muted = NO;
if (muted) {
[player setVolume:1.0];
} else {
[player setVolume:0.0];
}
muted = !muted;
}
swift 2+ solution
let musicPlayer:AVAudioPlayer = AVAudioPlayer()
var IsMuted:Bool = false
if IsMuted == false {
IsMuted = true
musicPlayer.volume = 0
} else {
IsMuted = false
musicPlayer.volume = 1
}
-> Don't forget to setCategory
to AVAudioSessionCategoryAmbient
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
try AVAudioSession.sharedInstance().setActive(true)
} catch _ {
return print("couldn't set session")
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.