簡體   English   中英

播放聲音文件iOS

[英]playing sound file iOS

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

從視圖返回后是否要播放此方法。 只需在- (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);
    }
}

您的viewDidLoad方法僅在視圖第一次出現時被調用。 為了使每次視圖出現時都能發生某些事情,請將您的代碼放入viewWillAppear:

確保從您的方法中調用[super viewWillAppear:animated]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM