【问题标题】:Toggling play/pause not working切换播放/暂停不起作用
【发布时间】:2012-02-02 16:53:33
【问题描述】:

收到{[audioPlayer pause];}saying Expected']' 的红色警告,并收到另一个红色警告消息[[audioPlayer play];]Expected expression

UIButton *playpauseButton = [UIButton buttonWithType:UIButtonTypeCustom];
[playpauseButton addTarget:self action:@selector(playpauseAction:) forControlEvents:UIControlEventTouchUpInside];
playpauseButton.frame = CGRectMake(0, 0, 50, 50);
[playpauseButton setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
[playpauseButton setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateSelected];

UIBarButtonItem *playpause = [[UIBarButtonItem alloc] initWithCustomView:playpauseButton];

动作代码:

-(void)playpauseAction:(UIButton *)sender
{   
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"theme" 
                                                     ofType:@"mp3"];
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];
    audioPlayer = [[AVAudioPlayer alloc] 
              initWithContentsOfURL:fileURL error:nil];

   [fileURL release];

   [audioPlayer prepareToPlay];

    audioPlayer.currentTime = 0;
    //[audioPlayer play];

     if  

  ([audioPlayer isPlaying]){

 Image:[UIImage imageNamed:@"play.png"] forState:UIControlStateSelected

 setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal

      {[audioPlayer pause];}

  } else {

setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateSelected


Image:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal


      [[audioPlayer play]; ]

  }


}

我需要帮助来修复此代码。

感谢您的帮助。

【问题讨论】:

    标签: iphone cocoa-touch avfoundation avaudioplayer


    【解决方案1】:

    您方法的整个播放/暂停部分是完全无效的 Objective-C。试试这个:

    if  ([audioPlayer isPlaying])
    {
        [sender setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
        [audioPlayer pause];
    }
    else
    {
        [sender setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
        [audioPlayer play];
    }
    

    另外,你真的不需要在那个方法中重新创建你的 audioPlayer。把它(“it”我的意思是“第一行和‘if’之间的那个方法中的所有东西”)放在你的-viewDidLoad 或其他东西中。

    【讨论】:

    • 现在播放按钮正在显示,当我点击播放按钮时,它正在播放音频文件并将播放按钮变成暂停按钮,但是当我点击暂停按钮暂停它时。它不是暂停,而是从头开始播放音频文件
    【解决方案2】:

    尝试设置委托并检查错误:

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"theme" ofType:@"mp3"];
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: [NSURL fileURLWithPath:filePath] error:&err];
    
    if( err ){
        NSLog(@"Failed with reason: %@", [err localizedDescription]);
    } else{
        //set our delegate and begin playback
        audioPlayer.delegate = self;
        [audioPlayer play];
    }
    

    顺便说一句,您绝对不希望每次按下按钮时都分配 audioPlayer,除非您首先检查它是否为 nil(第一次运行)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-24
      • 2019-06-25
      相关资源
      最近更新 更多