0

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

这是我的代码:

- (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);
    }
}
4

2 回答 2

0

如果您想在从视图返回后播放此方法。- (void)viewWillAppear:(BOOL)animated 只需在or - (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);
    }
}
于 2012-11-14T04:10:52.480 回答
0

您的viewDidLoad方法仅在视图第一次出现时被调用。要在每次视图出现时都发生一些事情,请将您的代码放入viewWillAppear:.

一定[super viewWillAppear:animated]要从你的方法调用。

于 2012-11-14T04:13:40.823 回答