OGeek|极客世界-中国程序员成长平台

标题: iphone - iOS - 如何在更改 View 时停止背景音乐 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 07:23
标题: iphone - iOS - 如何在更改 View 时停止背景音乐

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

- (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];
}

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



Best Answer-推荐答案


AVAudioPlayer *theAudio 创建一个属性,以便您可以从类(class)中的任何位置访问 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];
}

关于iphone - iOS - 如何在更改 View 时停止背景音乐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5764890/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4