播放声音文件iOS

时间:2012-11-14 04:08:54

标签: ios avaudioplayer nsdocumentdirectory

我正在使用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);
    }
}

2 个答案:

答案 0 :(得分: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);
    }
}

答案 1 :(得分:0)

仅在第一次显示视图时调用viewDidLoad方法。要在每次显示视图时发生某些事情,请将代码放在viewWillAppear:

请务必从您的方法中致电[super viewWillAppear:animated]