【问题标题】:iOS - How to stop background music when changing viewsiOS - 如何在更改视图时停止背景音乐
【发布时间】:2011-04-23 14:55:37
【问题描述】:

如何在更改视图时停止背景音乐?我没有线索。如果我按下一个将我带到新视图的按钮,就会有新的背景音乐。但旧的背景音乐(无限循环)仍在继续。请帮忙!也请示例一些代码,这是我的:

- (void)viewDidLoad {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"MathMusic2" ofType:@"wav"];
    AVAudioPlayer* theAudio= [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
    theAudio.delegate = self;
    [theAudio play];
    theAudio.numberOfLoops = -1;

    [super viewDidLoad];
}

我只需要知道如何让新视图中的背景音乐停止播放。当我在新视图中按下后退按钮时,反之亦然

【问题讨论】:

    标签: iphone objective-c xcode ios audio


    【解决方案1】:

    AVAudioPlayer *theAudio 创建一个属性,以便您可以从班级中的任何位置访问audioPlayer。

    viewController的头文件

    ... 
    AVAudioPlayer *theAudio;
    ...
    @property (nonatomic, retain) AVAudioPlayer *theAudio;
    

    viewController的实现文件

    ...
    @synthesize theAudio;
    ...
    
    - (void)viewDidLoad {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"MathMusic2" ofType:@"wav"];
        self.theAudio= [[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL]] autorelease];
        theAudio.delegate = self;
        [theAudio play];
        theAudio.numberOfLoops = -1;
    
        [super viewDidLoad];
    }
    

    如果 viewWillDisappear 被调用,你可以停止音频

    - (void)viewWillDisappear
    {
        [theAudio stop];
    }
    

    【讨论】:

      【解决方案2】:

      它在这里给出了错误: “theAudio.delegate = self;”就像分配给 id...

      反正它是黄色的.. 仍然当我改变观点并去另一堂课时音乐不停....

      【讨论】:

      • 在 viewController.h 中添加 AVAudioPlayerDelegate
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-22
      • 1970-01-01
      • 1970-01-01
      • 2016-10-14
      • 1970-01-01
      • 2010-12-12
      相关资源
      最近更新 更多