所以我在一个视图中播放背景音乐,然后按下按钮转到另一个视图,另一个视图中的背景音乐也会运行。 然后我有两个背景音乐播放。我想停止上一个视图中的音乐。
所以这是第一个视图的.h代码:
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface ViewController : UIViewController<AVAudioPlayerDelegate>{
AVAudioPlayer *startingMusic;
}
-(IBAction)StartGame:(id)sender;
所以这是第一个视图的.m代码:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
-(IBAction)StartGame:(id)sender{
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *music = [[NSBundle mainBundle] pathForResource:@"Morning_Walk" ofType:@"mp3"];
startingMusic=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:music] error:NULL];
startingMusic.delegate=self;
startingMusic.numberOfLoops=-1;
[startingMusic play];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
这是第二个视图的.h代码:
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface StageOne : UIViewController<AVAudioPlayerDelegate>
AVAudioPlayer *gameMusic;
}
这是第二个视图的.m代码:
#import "StageOne.h"
@interface StageOne ()
@end
@implementation StageOne
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
NSString *music = [[NSBundle mainBundle] pathForResource:@"Green_Hills" ofType:@"mp3"];
gameMusic=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:music] error:NULL];
gameMusic.delegate=self;
gameMusic.numberOfLoops=-1;
[gameMusic play];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
非常感谢你!
答案 0 :(得分:1)
这是正常行为,因为您的第一个控制器仍然已加载
试试这个:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear: animated];
NSString *music = [[NSBundle mainBundle] pathForResource:@"Green_Hills" ofType:@"mp3"];
gameMusic=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:music] error:NULL];
gameMusic.delegate=self;
gameMusic.numberOfLoops=-1;
[gameMusic play];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear: animated];
gameMusic.delegate = nil;
[gameMusic stop];
gameMusic = nil;
}