2012-06-15 66 views
-1

試圖添加設施以供用戶使用ui開關關閉我應用程序中的所有聲音。 (用戶偏好)使用ui開關關閉應用程序中的聲音xcode

- (IBAction)toggleaudio:(id)sender { 

    if (switchtoggle.on) 
    { 
     [self.????? play]; 
    } 
    else { 
     [self.?????? stop]; 
    } 
} 

我不確定要把問號放在我的代碼中。我試過的只是給了我錯誤。如果有更好的解決方案,我願意接受建議。

我對音頻代碼:

CFBundleRef mainBundle = CFBundleGetMainBundle(); 
CFURLRef soundFileURLRef; 
soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"btn2", CFSTR 
             ("mp3"), NULL); 
UInt32 soundID; 
AudioServicesCreateSystemSoundID (soundFileURLRef, &soundID); 
AudioServicesPlaySystemSound (soundID); 

回答

0

修正這個使用NS用戶默認

0

- (IBAction)toggleaudio:(id)sender { 

    if (switchtoggle.on) 
    { 
     CFBundleRef mainBundle = CFBundleGetMainBundle(); 
CFURLRef soundFileURLRef; 
soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"btn2", CFSTR 
             ("mp3"), NULL); 
UInt32 soundID; 
AudioServicesCreateSystemSoundID (soundFileURLRef, &soundID); 
AudioServicesPlaySystemSound (soundID); 
    } 
    else { 
     //nothings playing now 
    } 

    } 
+0

感謝您的回覆,即dosent關閉我的應用程序,所有的聲音,這只是播放的聲音,我怎麼讓用戶關閉所有的聲音效果? – JSA986

+0

當用戶點擊關閉時,只是不播放聲音?由於iOS不會播放聲音,因此您的應用會在代碼中發出聲音。所以有開關,並且可以使用NSUserDefaults來保存和加載開關,以檢查它是否打開或關閉。 – Maximilian

+0

爲什麼這個問題被標記出來,似乎是一個完全合理的問題? – JSA986

0

試一試這將播放的聲音上按下按鈕,如果開關狀態上播放聲音如果開關狀態關不播放聲音.. :) .h

@property (strong, nonatomic) IBOutlet UIButton *Btn; 
@property (strong, nonatomic) IBOutlet UISwitch *soundSwitch; 
- (IBAction)saveSwitchState:(id)sender; 
- (IBAction)ButtonPress:(id)sender 

.M

- (IBAction)saveSwitchState:(id)sender 
{ 

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; 

    if ([self.soundSwitch isOn]) 
    { 
     [defaults setBool:YES forKey:@"SwitchState"]; 
    [defaults synchronize]; 
     NSLog(@"Data Saved"); 
    } 
    else 
    { 
     [defaults setBool:NO forKey:@"SwitchState"]; 
     [defaults synchronize]; 
     NSLog(@"Data Saved"); 


    } 
} 
- (void)viewDidLoad//Load Default Switch State 
{ 
    [super viewDidLoad]; 
NSString *path = [[NSBundle mainBundle] 
    pathForResource:@"ding" ofType:@"mp3"]; 
    audioPlayer1 = [[AVAudioPlayer alloc]initWithContentsOfURL: 
    [NSURL fileURLWithPath:path] error:NULL]; 

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; 
    self.soundSwitch.on = [defaults boolForKey:@"SwitchState"]; 
} 
- (IBAction)ButtonPress:(id)sender 
if(self.soundSwitch.on==YES) 
    { 
    [audioPlayer1 play]; 
    } 
    else 
    {[audioPlayer1 stop]; 

    } 
}