我有一个iOS应用程序,其工作原理如下:
第一次观看 链接到不同视图的3个按钮,每个按钮都有自己的音频文件
想象一下,用户打开一个视图,然后开始播放音频文件。当他们在应用程序中导航时,音频文件仍在播放,这很好,我很高兴。
然而,如果用户然后打开第二个音频文件并按下播放,它将在第一个音频文件的顶部播放,因此2个音频正在一起播放。
如何告诉代码如果按下另一个播放按钮,它应该停止正在播放的第一个音频文件?
我正在使用AVFoundation框架来执行此操作
代码如下:
NSString *stringPath = [[NSBundle mainBundle]pathForResource:@"01" ofType:@"MP3"];
NSURL *url = [NSURL fileURLWithPath:stringPath];
NSError *error;
avPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
[avPlayer setNumberOfLoops:2];
[avPlayer setVolume:self.sliderVolumeOutlet.value];
[NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:@selector(updateMyProgress) userInfo:nil repeats:YES];
-(void)updateMyProgress
{
float progress = [avPlayer currentTime]/[avPlayer duration];
self.myProgressView.progress = progress;
}
- (IBAction)sliderVolumeAction:(id)sender {
UISlider *mySlider = sender;
[avPlayer setVolume:mySlider.value];
}
- (IBAction)stopButton:(id)sender {
[avPlayer stop];
[avPlayer setCurrentTime:0];
}
- (IBAction)pauseButton:(id)sender {
[avPlayer pause];
}
- (IBAction)playButton:(id)sender {
[avPlayer play];
}
- (IBAction)backButtonEvent:(id)sender {
[self dismissViewControllerAnimated:YES completion:NULL];
}
答案 0 :(得分:0)
您可以if ([AVPlayer rate] != 0.0)
检查是否正在播放上一首曲目
如果正在播放,则可以将下一首曲目添加到队列中,或者只使用此功能将当前曲目替换为新曲目- (void)replaceCurrentItemWithPlayerItem:(AVPlayerItem *)item
答案 1 :(得分:0)
也许创建某种playSound
函数会更适合这种情况。像这样:
- (void)playSoundWithFileName:(NSString *)fileName andExtension:(NSString *)extension {
NSString *stringPath = [[NSBundle mainBundle]pathForResource:fileName ofType:extension];
NSURL *url = [NSURL fileURLWithPath:stringPath];
NSError *error;
if (avPlayer) {
[avPlayer stop];
avPlayer = nil;
}
avPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
if (error)
NSLog(@"Error");
else {
[avPlayer setNumberOfLoops:2];
[avPlayer setVolume:self.sliderVolumeOutlet.value];
[avPlayer play];
}
}
使用:
[self playSoundWithFileName:@"01" andExtension:@"MP3"];
[NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:@selector(updateMyProgress) userInfo:nil repeats:YES];
并在您想播放其他声音时拨打-(void)playSoundWithFileName
。
或者如果您使用的是AVPlayer
类:
- (void)playSoundWithFileName:(NSString *)fileName andExtension:(NSString *)extension {
NSString *stringPath = [[NSBundle mainBundle]pathForResource:fileName ofType:extension];
NSURL *url = [NSURL fileURLWithPath:stringPath];
AVPlayerItem *item = [AVPlayerItem playerItemWithURL:url];
if (avPlayer)
[avPlayer replaceCurrentItemWithPlayerItem:item];
else
avPlayer = [AVPlayer playerWithPlayerItem:item];
[avPlayer setVolume:self.sliderVolumeOutlet.value];
[avPlayer play];
}
虽然后者不允许你设置一些循环。