0

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

#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

谢谢您的帮助!

4

1 回答 1

0

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

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

于 2013-08-03T22:41:16.017 回答