2013-08-03 70 views
0

我有2個ViewControllers,每個控制器都有幾個按鈕來播放和停止音頻。該音頻已經被部署在一個單獨的模型,以便能夠從兩個ViewControllers訪問,但我不知道這是正確的方式...如何從不同控制器控制AV播放器

#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 

感謝您的幫助!

+0

這個設計沒有什麼根本的錯誤,但是從你編寫AVPlayer代碼的方式來看,它看起來不會起作用。 –

+0

這就像每次我改變它的視圖啓用一個新的會話,我不知道可能是什麼... – elGeekalpha

回答

0

您正在爲每個控制器的viewDidLoad方法創建AudioController類的兩個不同實例。

您可以通過多種方式解決您的問題。例如,在單例中轉換AudioController類。

+0

它的工作原理,但我不能用物理控制或控制中心按鈕來控制播放器。謝謝!! – elGeekalpha