iOS:控制另一个View的AudioPlayer(控制器)

时间:2013-04-04 22:13:18

标签: ios avaudioplayer

我正在编写一个Quiz-App。在Menu-ViewController中,我将Music添加到项目中。 musicPlayer运行良好,只要Menu-ViewController在前面,我也可以控制它(播放,暂停,停止等)。当我显示另一个ViewController时,音乐在后台运行,就像我想的那样。但是如果尝试将第一个ViewController的播放/暂停方法调用在secondViewController中,则音乐网络暂停也不会停止。我不知道为什么!如果我在这个方法中添加其他说明,一切都很顺利。 (我尝试了exit(0);方法。这是我的代码:

控制器1 .h:

@implementation MenuViewController : <....> {
... }
@property (retain) AVAudioPlayer *backgroundPlayer;
- (void) playPauseMethod;

Controller 1 .m:

@interface ...
@end
@implementation MenuViewController 
@ synthesize 
- (void) soundChanger {
if (hintergrundPlayer.isPlaying) {
    [backgroundPlayer pause];}
else if (!backgroundPlayer.isPlaying) {
    [backgroundPlayer play];}}

控制器2 .h:

#import "MenuViewController.h"
@interface QuizViewController : UIViewController{}

Controller 2 .m:

@interface ...
@end
@implementation MenuViewController 
@ synthesize ...
//..... musicPlayer is playing music.
- (IBAction)myMusic:(id)sender {
//first try:
[[[MenuViewController alloc] init].backgroundPlayer pause];
//second try:
[[[MenuViewController alloc] init] soundChanger];}

我想控制每个ViewController中的音乐。我期待着你的帮助。

1 个答案:

答案 0 :(得分:0)

您正在使用

在Controller2中创建一个全新的MenuViewController
[[MenuViewController alloc] init]

处理它的最佳方法是在控制器2中设置一个类似

的协议
@protocol <Controller2Delegate>
-(void) playButtonPressed:(id)self;
@end

然后设置一个委托属性(仍在控制器2中),如下所示:

@property (weak) id <Controller2Delegate> delegate;

然后,在Controller 1中,当您创建Controller 2时,设置它的委托属性,如下所示:

QuizViewController *controller2 = [[QuizViewController alloc] init]];
controller2.delegate = self;

然后在控制器1中的某处创建playButtonPressed方法。在Controller 2中,您将执行以下操作:

[self.delegate playButtonPressed:self];

这将调用Controller 1中的方法,您可以暂停后台播放器。