如何在一个或多个 类 中控制 AVAudioPlayer?

How I can control AVAudioPlayer in one or more classes?

AppDelegate.m:我使用此代码启动 AVAudioPlayer,它适用于所有 SKScene。

#import "AppDelegate.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

{
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"game-sound" ofType:@"mp3"];
NSURL *file = [NSURL fileURLWithPath:soundFilePath];
_backgroundMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:file error:nil];
_backgroundMusic.numberOfLoops = -1;
_backgroundMusic.volume = 0.1;
[_backgroundMusic play];

return YES; }

AppDelegate.h:在header我添加了框架和AVAudioPlayer。

#import <AVFoundation/AVFoundation.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate, AVAudioPlayerDelegate> {

AVAudioPlayer *_backgroundMusic; }

Prefix.pch:在前缀中我添加了这一行:

#import "AppDelegate.h"

#define MyAppDelegate ((AppDelegate *)[[UIApplication sharedApplication] delegate])

我需要在 GameScene 中停止 AVAudioPlayer 并在 MenuScene 中继续播放。谁能帮我找到这个问题的解决方案?:)

您可以将 backgroundMusic 设为 public (AppDelegate.h):

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

 @interface AppDelegate : UIResponder <UIApplicationDelegate, AVAudioPlayerDelegate>

    @property (nonatomic, strong)AVAudioPlayer *backgroundMusic;

    @property (strong, nonatomic) UIWindow *window;

 @end

然后你可以像这样在你的场景中访问它(假设你的.pch文件设置为correctly):

[[MyAppDelegate backgroundMusic] stop];