2010-10-09 23 views
0

我正在尋找在視圖更改時停止播放音頻文件。viewDidUnload - 在視圖更改時停止方法

我正在使用tabController,我希望當用戶移動到不同的視圖時播放的音頻停止。我不確定我會在哪裏以及如何做到這一點。在viewDidUnload也許?

這裏是我用來播放音頻文件的方法:

- (無效){startPlaying [的NSTimer scheduledTimerWithTimeInterval:15目標:自我選擇:@selector(startPlaying)USERINFO:無重複:NO] ; NSString * audioSoundPath = [[NSBundle mainBundle] pathForResource:@「audio_file」ofType:@「caf」]; CFURLRef audioURL =(CFURLRef)[NSURL fileURLWithPath:audioSoundPath]; AudioServicesCreateSystemSoundID(audioURL,& audioID); AudioServicesPlaySystemSound(audioID); }

感謝您的幫助

回答

2

像這樣的事情在您的視圖控制器(未經測試):

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    // Load sample 
    NSString *audioSoundPath = [[NSBundle mainBundle] pathForResource:@"audio_file" 
                   ofType:@"caf"]; 
    CFURLRef audioURL = (CFURLRef)[NSURL fileURLWithPath:audioSoundPath]; 
    AudioServicesCreateSystemSoundID(audioURL, &audioID) 
} 

- (void)viewDidUnload 
{ 
    // Dispose sample when view is unloaded 
    AudioServicesDisposeSystemSoundID(audioID); 

    [super viewDidUnload]; 
} 

// Lets play when view is visible (could also be changed to viewWillAppear:) 
- (void)viewDidAppear:(BOOL)animated 
{ 
    [super viewDidAppear:animated]; 

    [self startPlaying]; 
} 

// Stop audio when view is gone (could also be changed to viewDidDisappear:) 
- (void)viewWillDisappear:(BOOL)animated 
{ 
    [super viewWillDisappear:animated]; 

    if([self.audioTimer isValid]) { 
     [self.audioTimer invalidate]; 
    } 
    self.timer = nil; 
} 

// Start playing sound and reschedule in 15 seconds. 
-(void)startPlaying 
{ 
    self.audioTimer = [NSTimer scheduledTimerWithTimeInterval:15 target:self 
                selector:@selector(startPlaying) 
                userInfo:nil 
                 repeats:NO]; 
    AudioServicesPlaySystemSound(audioID); 
} 

缺少:

  • 錯誤檢查
  • 物業或伊娃的audioTimer 。
  • 也可以保持相同的計時器,重複YES。
  • 釋放dealloc中的資源。
  • 測試
+0

感謝您的帖子。 – hanumanDev 2010-10-10 16:04:23

+0

不客氣。 – dlundqvist 2010-10-11 15:35:53

相關問題