2012-11-14 55 views
0

我正在播放viewDidLoad方法中的声音文件。声音文件保存在文档目录中。当第一次加载视图时,它会成功播放。但是当我弹出这个视图并回来时,它不会播放。播放声音文件iOS

这里是我的代码:

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 

    NSString *localFilePathSound =[[NSString alloc] initWithString:[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"sound.caf"]]]; 

    if ([[NSFileManager defaultManager] fileExistsAtPath:localFilePathSound]) { 
     //NSString *clapPath = [[NSBundle mainBundle] pathForResource:@"scaryVoice" ofType:@"wav"]; 
     CFURLRef clapURL = (CFURLRef) [NSURL fileURLWithPath:localFilePathSound]; 
     AudioServicesCreateSystemSoundID (clapURL, &clappingFileId); 
     AudioServicesPlaySystemSound(clappingFileId); 
    } 
    // Do any additional setup after loading the view from its nib. 
    else{ 
     NSString *clapPath = [[NSBundle mainBundle] pathForResource:@"scaryVoice" ofType:@"wav"]; 
     CFURLRef clapURL = (CFURLRef) [NSURL fileURLWithPath:clapPath]; 
     AudioServicesCreateSystemSoundID (clapURL, &clappingFileId); 
     AudioServicesPlaySystemSound(clappingFileId); 
    } 
} 

回答

0

如果你想从一个视图回来后玩这个方法。 只需将上面的代码写入- (void)viewWillAppear:(BOOL)animated- (void)viewDidAppear:(BOOL)animated方法即可。

- (void)viewWillAppear:(BOOL)animated 
{ 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 

    NSString *localFilePathSound =[[NSString alloc] initWithString:[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"sound.caf"]]]; 

    if ([[NSFileManager defaultManager] fileExistsAtPath:localFilePathSound]) 
    { 
     //NSString *clapPath = [[NSBundle mainBundle] pathForResource:@"scaryVoice" ofType:@"wav"]; 
     CFURLRef clapURL = (CFURLRef) [NSURL fileURLWithPath:localFilePathSound]; 
     AudioServicesCreateSystemSoundID (clapURL, &clappingFileId); 
     AudioServicesPlaySystemSound(clappingFileId); 
    } 
    // Do any additional setup after loading the view from its nib. 
    else 
    { 
     NSString *clapPath = [[NSBundle mainBundle] pathForResource:@"scaryVoice" ofType:@"wav"]; 
     CFURLRef clapURL = (CFURLRef) [NSURL fileURLWithPath:clapPath]; 
     AudioServicesCreateSystemSoundID (clapURL, &clappingFileId); 
     AudioServicesPlaySystemSound(clappingFileId); 
    } 
} 
+0

还有问题吗? –

+0

是的,我尝试过,但仍面临同样的问题 –

0

您的viewDidLoad方法仅在第一次出现视图时被调用。为了在每次出现视图时发生,请将代码放入viewWillAppear:

一定要从您的方法呼叫[super viewWillAppear:animated]