如何停止播放歌曲,播放新歌



我正在开发应用程序,我有一个问题,当我点击按钮,然后选择索引歌曲开始,但我想停止这首歌,并想播放下一首歌曲,索引我给然后,两首歌开始播放。意思是上一个连续,下一个也在播放。请指导我如何停止以前的歌曲和下一个只开始播放。代码在这里

  - (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];
}

Try This:

   -(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]; 
        }
    }

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];

最新更新