[英]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.