我有一个按钮,在播放和暂停图像之间切换当点击。当播放图像显示时,一个环形声音正在播放,当显示暂停图像时,声音停止播放。
我必须设法让它发挥作用,但有一个问题。当你点击按钮暂停(停止),它播放声音最后一次(因此暂停行动被延迟的秒数的声音)。
这是我的密码:
@implementation ViewController
AVAudioPlayer *myAudio;
- (void)viewDidLoad {
[super viewDidLoad];
[self.myButton setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
[self.myButton setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateSelected];
}
- (IBAction)buttonTapped:(id)sender {
NSURL *musicFile;
musicFile = [NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"]];
myAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:nil];
if(self.myButton.selected)
[self.myButton setSelected:NO];
else
[self.myButton setSelected:YES];
if(self.myButton.selected)
[myAudio setNumberOfLoops:-1];
[myAudio play];
}发布于 2017-05-10 11:36:15
你所做的是在每次点击按钮时创建一个播放器。
您应该尝试创建一个AVPlayer (在viewDidLoad中),并在buttonTapped:函数中使用它的play和pause函数。
- (void)viewDidLoad {
[super viewDidLoad];
[self.myButton setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
[self.myButton setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateSelected];
NSURL *musicFile = [NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"]];
myAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:nil];
}
- (IBAction)buttonTapped:(id)sender {
[self.myButton setSelected:!self.myButton.selected];
if (self.myButton.selected) {
[player seekToTime:kCMTimeZero];
[player play];
}
else {
[player pause];
}
}单击按钮将首先切换它的状态(选择与否),然后根据它的状态,播放器将倒带并开始播放,或暂停自身(立即)。
https://stackoverflow.com/questions/43890868
复制相似问题