How to have a Slider in a class view controller that changes the volume of a song playing in the AppDelage, in Objective-C for iOS? Here is my code in the .h AppDelegate
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface JARAppDelegate : UIResponder <UIApplicationDelegate>
{
AVAudioPlayer *musicPlayer;
}
@property (strong, nonatomic) UIWindow *window;
- (void)playMusic;
- (void)setVolume:(float)vol;
@end
And in the .m:
- (void)playMusic
{
NSString *musicPath = [[NSBundle mainBundle] pathForResource:@"The History of the World" ofType:@"mp3"];
NSURL *musicURL = [[NSURL alloc] initFileURLWithPath:musicPath];
musicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL error:nil];
[musicPlayer setNumberOfLoops:-1]; // Negative number means loop forever
[musicPlayer setVolume:1.0];
[musicPlayer prepareToPlay];
[musicPlayer play];
NSLog(@"play");
}
- (void)setVolume:(float)vol
{
[musicPlayer setVolume:vol];
}
and when 'didFinishLaunchingWithOptions' I call [self playMusic];
This works and plays the song I want a full volume! Then in a different class called SettingsViewControler:
The .h
#import <UIKit/UIKit.h>
#import "JARAppDelegate.h"
@interface JARSettingsViewController : UIViewController
{
}
@property (strong, nonatomic) IBOutlet UISlider *volumeSliderOutlet;
- (IBAction)volumeSliderActoin:(id)sender;
@end
The .m:
- (IBAction)volumeSliderActoin:(id)sender
{
NSLog(@"Volume Changed");
[JARAppDelegate setVolume:sender];
}
Volume Changed is logged everytime you move the slider up and down, and so it should be sending setVolume a value between 0.0 and 1.0. But I get an error that says "No known class method for selector 'setVolume:'
This is because you are trying to invoke a class method when you call:
[JARAppDelegate setVolume:sender];
but this doesn't exist. You have created an instance method.
Try creating a singleton for the AVAudioPlayer, then you could do the following:
[[AVAudioPlayer sharedInstance] setVolume:vol];