ios - 如何停止在 Xcode 中播放不同类的背景音乐?

标签 ios objective-c xcode audio avaudioplayer

我已设置要在 ViewController.h 和 .m 文件中播放的音乐轨道,如下所示。我想在加载新场景时停止此操作。 (.h):

@interface ViewController : UIViewController<AVAudioPlayerDelegate>{

    AVAudioPlayer *startingMusic;

}

@property (nonatomic, retain) AVAudioPlayer *startingMusic;

@end

然后是.m

@synthesize startingMusic;
- (void)viewDidLoad
{
    [super viewDidLoad];
    NSString *music = [[NSBundle mainBundle] pathForResource:musicTrack ofType:@"mp3"];
    startingMusic=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:music] error:NULL];
    startingMusic.delegate=self;
    startingMusic.numberOfLoops=-1;
    [startingMusic play];
}

然后,当新场景加载时,我尝试使用此代码在 init 方法中阻止其播放,该类名为 PlayLevel.m。

ViewController *test = [[ViewController alloc] init];
[test.startingMusic stop];

但是,当新的内容加载时,音乐会继续播放。有什么建议吗?

最佳答案

当您执行 ViewController *test = [[ViewController alloc] init]; 操作时,您创建了新的 ViewController 实例,这意味着内存中现在有两个 ViewController 的对象。

您真正需要做的是对当前的调用调用stop

如果您想停止来自另一个与您的 ViewController 没有连接的 Controller 的音乐,您可以尝试通过通知执行此操作。

例如:

在您的 ViewController.h 文件中,导入后:

static NSString * const kStopMusicNotificationName = @"kStopMusicNotificationName";

在你的ViewController viewDidLoad中:

[NSNotificationCenter.defaultCenter addObserverForName:kStopMusicNotificationName object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
        [self.startingMusic stop];
    }];

当您需要停止音乐时:

[NSNotificationCenter.defaultCenter postNotificationName:kStopMusicNotificationName object:nil];

关于ios - 如何停止在 Xcode 中播放不同类的背景音乐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28608480/

相关文章:

ios - 在 iOS 中实现本地服务器

ios - 显示下拉表时的自动布局问题

objective-c - UIImageView - 固定宽度和灵活高度?

ios - 如何只获取 NSUrl 数组的文件名

ios - 在 objective-c 的选定日期中使用 dateWithTimeInterval 添加 3 秒后获取无效时间

swift - 隐藏后状态栏仍然显示为黑色

c++ - SFML 图像未加载

iOS - 在父级插入 AnotherVC 后如何在 NavigationController 堆栈中找到 ChildVC

ios - AVPlayer seekToTime : backward not working

ios - Swift 3 - 尝试执行获取请求时程序崩溃