如何在类视图控制器中使用Slider来改变AppDelage中播放的歌曲的音量,在Objective-C中为iOS?

时间:2012-08-14 22:57:57

标签: iphone objective-c ios avaudioplayer uislider

如何在类视图控制器中使用Slider来改变AppDelage中播放的歌曲的音量,在Objective-C for iOS中? 这是我在.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

在.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];
}

当'didFinishLaunchingWithOptions'时,我呼叫[self playMusic]; 这可以播放我想要的音量!然后在另一个名为SettingsViewControler的类中: .h

#import <UIKit/UIKit.h>
#import "JARAppDelegate.h"

@interface JARSettingsViewController : UIViewController
{

}

@property (strong, nonatomic) IBOutlet UISlider *volumeSliderOutlet;

- (IBAction)volumeSliderActoin:(id)sender;

@end

.m:

- (IBAction)volumeSliderActoin:(id)sender
{
     NSLog(@"Volume Changed");
     [JARAppDelegate setVolume:sender];
}
每次向上和向下移动滑块时都会记录 Volume Changed,因此应该向setVolume发送介于0.0和1.0之间的值。但是我得到一个错误,上面写着“没有已知的选择器类方法'setVolume:'

1 个答案:

答案 0 :(得分:1)

这是因为您在调用时尝试调用方法:

[JARAppDelegate setVolume:sender];

但这不存在。您已创建实例方法。

尝试为AVAudioPlayer创建单例,然后您可以执行以下操作:

[[AVAudioPlayer sharedInstance] setVolume:vol];