2010-10-04 49 views
0

我正在使用AVAudioPlayer來管理一些聲音,但isPlaying方法似乎崩潰了。AVAudioPlayer正在播放崩潰的應用程序

當我開始做頁:

self.soundClass = [AVAudioPlayer alloc]; 

我怎麼打了聲:

-(void)playSound:(NSString *)fileName:(NSString *)fileExt { 

    if ([self.soundClass isPlaying]){ 
     [self.soundClass pause]; 
    } 
    else if (newSoundFile == currentSoundFile) { 
     [self.soundClass play]; 
    } 
    else { 
     NSLog(@"PlaySound with two variable passed function"); 
     [[NSBundle mainBundle] pathForResource: fileName ofType:fileExt]], &systemSoundID); 

     [self.soundClass initWithContentsOfURL:[NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource: fileName ofType:fileExt]] error:nil]; 

     [self.soundClass prepareToPlay]; 
     [self.soundClass play]; 
    } 

    self.currentSoundFile = fileName; 

} 

我soundClass是很空的現在:

soundclass.h

#import <UIKit/UIKit.h> 
#import <AudioToolbox/AudioToolbox.h> 
#import<AVFoundation/AVFoundation.h> 


@interface SoundClass : AVAudioPlayer <AVAudioPlayerDelegate> { 

} 

@end 

SoundCl ass.m

#import "SoundClass.h" 

@implementation SoundClass 
-(void)dealloc { 


    [super dealloc]; 
} 

@end 

你在這裏看到什麼我可能會做錯嗎?它崩潰在if (isPlaying)

回答

2

您指向在您列出的第一行中爲AVAudioPlayer的實例分配的空間,但實際上並未初始化實例。在Cocoa中,「alloc」是99.9%的時間,後跟某種形式的-init(如-initWithContentsOfURL:error:在AVAudioPlayer的情況下)。

此外,「soundClass」是一個實例變量的奇怪名稱。您應該瞭解一個類(對象的藍圖)和類的實例(從藍圖構建的實際對象)之間的區別。對這個概念的深入瞭解對於你理解Cocoa(以及所有面向對象)的編程至關重要。

+0

嗯,當我開始時,程序還沒有被告知要玩什麼,我可以初始化什麼?或者我應該加載一些東西?如果我改變剪輯,我只是​​重新initWithContentsOfURL? – emachine 2010-10-04 19:47:54

+0

在這種情況下,將其設置爲零。這通常是在你的類的init ...方法(「self」指向這種情況的實例的類)中完成的。 – 2010-10-04 19:52:04

+0

so self.soundClass = nil?這不是設置它被刪除? – emachine 2010-10-04 20:01:22