ios - 如何停止播放歌曲和播放新歌曲

标签 ios objective-c audio

我正在开发应用程序,但有一个问题,当我单击按钮时,选定的索引歌曲开始播放,但是我想停止播放这首歌曲,然后播放下一首我给出索引的歌曲,这两首歌曲都开始播放。表示上一个连续播放,下一个也播放。
请指导我如何停止上一首歌,然后下一首才开始播放。
代码在这里

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

最佳答案

试试这个:

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

        }
    }

关于ios - 如何停止播放歌曲和播放新歌曲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24880726/

相关文章:

ios - 将多个图像发送到 Web 服务器

ios - iOS 上的 AVCaptureAudioFileOutput 在哪里?

ios - UNNotificationSound.default() 是什么声音?

javascript - scriptNode.onaudioprocess 已弃用,还有其他选择吗?

ios - 从字符串中删除多个换行符/回车符

ios - UIApplication.sharedApplication 不可用

ios - 将文件上传到ftp服务器时遇到问题

ios - 无法使用标识符单元 XX 错误使单元出队 - 无法弄清楚如何解决

iphone - iOS 测试驱动开发 : Testing a method that uses UIVIew animateWithDuration:animations:completion:

iphone - 添加 SQLcipher sqlite3_exec 后返回 SQLITE_NOTADB