gpt4 book ai didi

ios - 如何在切换 ViewController 时保持背景音乐播放?

转载 作者:行者123 更新时间:2023-11-29 11:46:35 25 4
gpt4 key购买 nike

我目前有一个 SettingsViewController,它处理开始/停止音乐和调整音乐音量。

是否可以在 SettingsViewController 展开后继续播放音乐?在打开音乐并切换 ViewControllers 后,我可以重新打开 SettingsViewController 并关闭音乐吗?请让我知道限制。

这是我的 SettingsViewController.h 的代码

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface SettingsViewController : UIViewController <AVAudioPlayerDelegate>
{
AVAudioPlayer *audioPlayer;
IBOutlet UISwitch *Switch;
IBOutlet UISlider *Slider;

}
-(IBAction)Switch:(UISwitch *)sender;
-(IBAction)Slider:(UISlider *)sender;
@end

这是我的 SettingsViewController.m 的代码

#import "SettingsViewController.h"

@interface SettingsViewController ()

@end

@implementation SettingsViewController

-(IBAction)Switch:(UISwitch *)sender{
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];

if(sender.tag == 0){
if(sender.on){
[standardDefaults setObject:@"On" forKey:@"keyName"];
//choosing and setting the music file
NSString *music = [[NSBundle mainBundle]pathForResource:@"bgmusic1" ofType:@"mp3"];
audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:music] error:NULL];
audioPlayer.delegate = self;
audioPlayer.numberOfLoops= -1; //sets the music to loop infinitely
[audioPlayer play]; //plays the music


} else if (sender.on == 0){
[standardDefaults setObject:@"Off" forKey:@"keyName"];
[audioPlayer stop]; //stops the music
}
}
[standardDefaults synchronize];

}

-(IBAction)Slider:(UISlider *)sender{
audioPlayer.volume = sender.value / 100.0; //will adjust the volume of the music according the slider value
}

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

让我知道需要修改什么!

最佳答案

在您的 AppDelegate 中执行此操作。

要从任何地方访问它,将它的 .h 文件导入到您的 ViewControllers .m 文件中并使用

MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];

将音频播放器设为 AppDelegate.h 中的一个属性以允许公共(public)访问(例如您的其他 viewController)

@interface AppDelegate: NSAppDelegate
{
IBOutlet UISwitch *Switch;
IBOutlet UISlider *Slider;
}

@property AVAudioPlayer *audioPlayer; // <------
-(IBAction)Switch:(UISwitch *)sender;
-(IBAction)Slider:(UISlider *)sender;
@end

然后在 m 文件中调整音频播放器的每次调用以采用 h 文件中的更改。

//Instead of [audioplayer doSomething] write...
[self.audioplayer doSomething];

// in modern objective-c you can use also
[_audioplayer doSomething];

要从其他 ViewController 调用您的音频播放器,然后实现第一个提到的代码并像这样调用您的播放器

[appDelegate.audioplayer doSomething]

关于ios - 如何在切换 ViewController 时保持背景音乐播放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43463476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com