【发布时间】:2016-06-05 15:45:18
【问题描述】:
因此,如果我留在同一个视图控制器上,我的音频工作正常,音乐会按我想要的方式打开和关闭。但是,当我使用不同的头文件模态到另一个视图控制器并返回到我原来的视图控制器时,我不能再打开或关闭我的音乐。这是我的代码:
-(void) viewDidLoad {
//Play Background Music in .1 second after game loads
[self performSelector:@selector(playBackgroundMusic) withObject:nil afterDelay:0.1];
}
-(void) playBackgroundMusic {
//Music int is used so music doesnt play over itself
if (musicInt == 0) {
NSString* resourcePath = [[NSBundle mainBundle] resourcePath];
resourcePath = [resourcePath stringByAppendingString:@"/JungleMusic.wav"];
NSLog(@"Path to play: %@", resourcePath);
NSError* err;
//Initialize our player pointing to the path to our resource
player = [[AVAudioPlayer alloc] initWithContentsOfURL:
[NSURL fileURLWithPath:resourcePath] error:&err];
musicInt = musicInt + 1;
//set our delegate and begin playback
player.delegate = self;
[player play];
player.numberOfLoops = -1;
player.currentTime = 0;
player.volume = 1.0;
}
}
//Used to turn the music on or off
-(IBAction)musicTest:(id)sender{
if (player.playing) {
[player stop];
} else {
[player play];
}
}
我还在同一个 .m 文件中合成了我的播放器:
@synthesize player;
在我的 .h 文件中,我声明了 AVAudioPlayer
@interface ViewController1 : UIViewController <AVAudioPlayerDelegate>
{
AVAudioPlayer *player;
}
@property (nonatomic, retain) AVAudioPlayer *player;
任何解决此问题的帮助将不胜感激。我只是不明白为什么在简单地建模到另一个视图控制器之后我不能打开/关闭我的音频?谢谢!
【问题讨论】:
-
为了能够开始和停止您的音乐,您首先需要能够与正在播放它的视图控制器进行通信。你是如何从你的第一个音乐播放视图控制器到你的第二个 VC 的,你又是如何回来的?您是否将第二个 VC 呈现为模态,然后将其驳回?推入导航堆栈然后弹出?
-
@DuncanC 感谢您的回复。该应用程序是基于情节提要的,并为视图控制器留下一个模态,并在每次单击按钮时返回一个模态。我不确定推送到导航堆栈和弹出是什么。
-
返回模式是错误的。您正在创建无穷无尽的模式系列。当您使用模态“返回”时,您根本不会返回。您正在创建原始 VC 的新实例并将其放在模态堆的顶部。您要么需要使用展开转场,要么让后退按钮调用 IBAction 而不是转场,其中动作调用 `dismissViewController:animated:completion:
-
我对其进行了更改,现在可以使用了!感谢您的帮助,我使用了 [self dismissViewControllerAnimated:YES completion:nil];代替我的后退按钮,它解决了这个问题! @DuncanCpan>
-
请礼貌地接受解决您问题的答案。 (-:
标签: ios objective-c audio model-view-controller avaudioplayer