如何从不同的控制器控制AV播放器

时间:2013-08-03 20:29:54

标签: ios model-view-controller avplayer

我有2个ViewControllers,每个都有几个按钮可以播放和停止音频。此音频已部署在一个单独的模型中,以便能够从两个ViewControllers访问,但我不知道这是否正确...

#import <UIKit/UIKit.h> 
#import "AudioController.h"

@interface NowViewController : UIViewController

@property (nonatomic, strong) AudioController *AudioModel;

- (IBAction)PauseButton:(UIButton *)sender;
- (IBAction)PlayButton:(UIButton *)sender;

@end

#import "NowViewController.h"

@interface NowViewController ()

@end

@implementation NowViewController

- (void)viewDidLoad{

    [super viewDidLoad];
    self.AudioModel = [[AudioController alloc] init];

}

- (IBAction)PlayButton:(UIButton *)sender {

    [self.AudioModel PlayAudio];

}

- (IBAction)PauseButton:(UIButton *)sender {

    [self.AudioModel PauseAudio];
}

@end

#import <UIKit/UIKit.h>

#import "AudioController.h"

@interface CategoriesViewController : UIViewController

@property (nonatomic, strong) AudioController *AudioModel;

- (IBAction)PauseButton:(UIButton *)sender;
- (IBAction)PlayButton:(UIButton *)sender;

@end

#import "NowViewController.h"

@interface NowViewController ()

@end

@implementation NowViewController

- (void)viewDidLoad{
    [super viewDidLoad];
    self.AudioModel = [[AudioController alloc] init];
}

- (IBAction)PlayButton:(UIButton *)sender {
    [self.AudioModel PlayAudio];
}

- (IBAction)PauseButton:(UIButton *)sender {
    [self.AudioModel PauseAudio];
}

@end

我遇到的问题是,如果我从一个页面播放音频并导航到另一个页面,那么我无法停止音频。同样,我无法从多任务中播放/暂停。这是AudioModel的代码:

#import <Foundation/Foundation.h>   
#import <AVFoundation/AVFoundation.h>

@interface AudioController : NSObject{

    AVPlayer *Player;
}

- (void)PlayAudio;
- (void)PauseAudio;

@end

#import "AudioController.h"

@implementation AudioController

- (void)PlayAudio {
    Player = [[AVPlayer alloc] initWithURL:[NSURL URLWithString:url]];
    [Player play];
}

- (void)PauseAudio {

    [Player pause];
}

NSString *url = @"http://jo.my/xxx";

@end

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您正在每个控制器的AudioController方法中创建两个不同的viewDidLoad类实例。

您可以通过多种方式解决问题。例如,在单例中转换AudioController类。