【问题标题】:How to stop playing song and play new song如何停止播放歌曲并播放新歌
【发布时间】:2023-04-03 03:44:01
【问题描述】:
我正在开发应用程序,我有一个问题,当我单击按钮然后选择的索引歌曲开始但我想停止这首歌并想播放我给的索引的下一首歌曲时,两首歌曲都开始播放。表示上一个连续,下一个也在播放。
请指导我如何停止上一首歌曲,下一首才开始播放。
代码在这里
- (IBAction)play:(id)sender
{
[self.audioPlayer stop];
self.audioPlayer = nil;
self.audioPlayer.currentTime = 0;
if(self.audioPlayer.playing ==YES)
{
self.audioPlayer.delegate=nil;
[self.audioPlayer stop];
self. audioPlayer=nil;
NSLog(@"plat");
}
NSString *path=[[NSBundle mainBundle]pathForResource:sound.text ofType:@"mp3"];
self.audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:
[NSURL fileURLWithPath:path] error:NULL];
//self.audioPlayer = nil;
[self.audioPlayer play];
}
【问题讨论】:
标签:
ios
objective-c
audio
【解决方案1】:
试试这个:
-(void)playSound
{
NSString *path=[[NSBundle mainBundle]pathForResource:sound.text ofType:@"mp3"];
self.audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:
[NSURL fileURLWithPath:path] error:NULL];
[self.audioPlayer play];
}
- (IBAction)play:(id)sender
{
if (self.audioPlayer.playing == NO)
{
[self playSound];
}
else
if (self.audioPlayer.playing == YES) {
[self.audioPlayer stop];
[self playSound];
}
}
【解决方案2】:
OK 使用AVQueuePlayer 用于按顺序播放多个项目。
NSString *secondPath = [[NSBundle mainBundle] pathForResource:@"s1" ofType:@"mp3"];
NSString *firstPath = [[NSBundle mainBundle] pathForResource:@"s2" ofType:@"mov"];
AVPlayerItem *firstVideoItem = [AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:firstPath]];
AVPlayerItem *secondVideoItem = [AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:secondPath]];
self.queuePlayer = [AVQueuePlayer queuePlayerWithItems:[NSArray arrayWithObjects:firstVideoItem, secondVideoItem,nil]];
[self.queuePlayer play];