是否可以使用按钮自动播放音频和播放/暂停?
Posted
技术标签:
【中文标题】是否可以使用按钮自动播放音频和播放/暂停?【英文标题】:Is it possible to autoplay audio and play/pause with button? 【发布时间】:2013-06-13 11:23:59 【问题描述】:我需要在打开视图后自动播放音频并有一个按钮来控制播放/暂停事件。我听说它有一个prepareToPlay
可以通过按钮控制音频,但它不能自动播放音频。
这是我的代码:
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:@"track8"
ofType:@"mp3"]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
[audioPlayer prepareToPlay];
在按钮中:
-(IBAction)playPauseButtonPress:(id)sender
if (self.isPlaying)
[self.audioPlayer pause];
self.isPlaying = NO;
else
[self.audioPlayer play];
self.isPlaying = YES;
是否可以通过按钮自动播放音频和播放/暂停?怎么样?
【问题讨论】:
【参考方案1】:NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:@"track8"
ofType:@"mp3"]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
[audioPlayer prepareToPlay];
有方法play
可用于播放它。您只需要添加以下行:
[audioPlayer play];
请查看AVAudioPlayer documentation
播放 >
Calling this method implicitly calls the prepareToPlay method if the audio player is not already prepared to play.
prepareToPlay > Calling this method preloads buffers and acquires the audio hardware needed for playback, which minimizes the lag between calling the play method and the start of sound output.Calling the stop method, or allowing a sound to finish playing, undoes this setup.
如果您使用play
而不是prepareToPlay
,则没有什么不能暂停音频。
希望对你有帮助
【讨论】:
是的,它有,但如果我使用 'play' 方法,'prepareToPlay' 方法不起作用 为什么要使用prepareToPlay
?如果您直接使用play
,它将在启动时播放,即使您可以使用暂停/播放。以上是关于是否可以使用按钮自动播放音频和播放/暂停?的主要内容,如果未能解决你的问题,请参考以下文章