我在我的应用程序中使用 avaudioplayer。在 viewwilldisappear 我想暂停/停止声音,在 viewwill 出现我想再次播放声音。我该怎么做?我在 viewWillAppear 上使用此代码:-
if(self.TickPlayer)
{
[self.TickPlayer play];
}
if(self.TickPlayer.volume<0)
{
self.TickPlayer.volume=1.0;
}
这在 viewWillDisAppear
if(self.TickPlayer)
{
[self.TickPlayer stop];
}
这是播放声音的方法
-(void)PlayTickTickSound:(NSString*)SoundFileName
{
//Get the filename of the sound file:
NSString *path = [NSString stringWithFormat:@"%@%@",[[NSBundle mainBundle] resourcePath],[NSString stringWithFormat:@"/%@",SoundFileName]];
//Get a URL for the sound file
NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
NSError *error;
if(self.TickPlayer==nil)
{
self.TickPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:filePath error:&error];
// handle errors here.
self.TickPlayer.delegate=self;
[self.TickPlayer setNumberOfLoops:-1]; // repeat forever
[self.TickPlayer play];
}
if(self.TickPlayer)
{
[self.TickPlayer play];
}
}
我在使用计时器每秒触发的方法中调用它
在 viewDidLoad-
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats:YES];
-(void) updateCountdown {
[self PlayTickTickSound:@"tick.caf"];
}
当警报出现时,我还在特定条件下使用 avaudioplayer 播放哔声。效果很好,但这没有按预期工作