I’m trying to change the volume of a sound effect via a variable. I’m using AVAudioPlayer and calling the variable to set volume, however when I run the app I get no sound at all, regardless of the variable setting. (.1-1.0) However if I set the number from within the AvAudioPlayer block (player.volume = .5;) then it responds as it should. Any ideas what I’m doing wrong?
Example of my code:
@interface
@property (nonatomic) float setVolume;
@implementation
@synthesize setVolume;
float setVolume = .5;
-(void)countdown
{
//play sound
NSString *musicFilePath = [[NSBundle mainBundle] pathForResource:@"Countdown_beep" ofType:@"wav"];
NSURL *musicURL = [[NSURL alloc] initFileURLWithPath:musicFilePath];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL error:nil];
player.volume = setVolume;
[player play];
Thanks. 🙂
EDIT:
I fixed the problem by removing the declaration from the header file and creating the ivar within the implementation.
This line makes no sense and is irrelevant to your program:
You are already synthesizing a property/ivar called
setVolume. This isn’t it. So by default your propertysetVolumeis zero and you are doing nothing to change that, so the volume is ending up as zero and no sound is happening.To set the value of the property, set the value of the property. 🙂 For example, you could say
self.setVolume = .5. You could do that earlier in thecountdownmethod, for example, or in some other method (one of the points of a property is that all methods of this object can see it).Now, another issue with your code is that your property name begins with “set”. This is probably a bad idea. If I were you, I’d pick another name. Names of the form “setX” are best used only as the name of a setter method for an instance variable / property X.