如果用户单击ios中AVAudioPlayer中的“播放”按钮,如何显示“暂停”按钮

时间:2014-03-19 04:42:30

标签: ios objective-c iphone xcode avaudioplayer

您好我正在根据我的项目要求开发AVAudioplayer。我正在以编程方式创建audioplayer。如果用户点击播放按钮,我想显示暂停按钮。我写了一些代码。如果我点击播放按钮,不应显示暂停按钮。所以请帮助我任何人。提前谢谢。

-(void)viewDidLoad
{

playButton=[[UIButton alloc]init];

playButton.frame=CGRectMake(125, 120, 29, 29);

playButton.backgroundColor=[UIColor clearColor];

playbackgroundImage=[UIImage imageNamed:@"play.png"];

[playButton setImage:playbackgroundImage forState:UIControlStateNormal];

[playButton addTarget:self action:@selector(playOrPauseButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:playButton];

}

-(void)playOrPauseButtonPressed:(id)sender
{
if(playing==NO)
{
      [playButton setBackgroundImage:[UIImage imageNamed:@"Pause.png"] forState:UIControlStateNormal];

// Here Pause.png is a image showing Pause Button.

NSError *err;

AVAudioSession *audioSession=[AVAudioSession sharedInstance];

[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];

NSData *data=[NSData dataWithContentsOfURL:url];

audioPlayer=[[AVAudioPlayer alloc]initWithData:data error:&err];

[audioPlayer prepareToPlay];

audioPlayer.delegate=self;

[audioPlayer play];

playing=YES;

}

else if (playing==YES)

{

[playButton setBackgroundImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];

[audioPlayer pause];

playing=NO;

}

}

1 个答案:

答案 0 :(得分:1)

问题是您首次设置 Setimage ,而playOrPauseButtonPressed设置 SetBackgroundImage 。 所以在viewDidLoad

中替换此方法
 [playButton setBackgroundImage:playbackgroundImage forState:UIControlStateNormal];