【发布时间】:2015-02-20 08:18:35
【问题描述】:
我用按钮歌曲创建了一个视图。
当我们点击按钮时,它会进入一个包含歌曲列表的表格。 当我们选择一首歌曲时,它会转到另一个视图并播放歌曲。 每当歌曲播放时,我们都可以返回主视图或歌曲表,这首歌将在后台播放,直到此处为止。
但每当我尝试播放歌曲表中的另一首歌曲时,前一首歌曲不会停止,它会继续与所选歌曲一起播放。
我的目标是在切换到不同视图时播放歌曲。我已经完成了这个,但我想要的是每当我从歌曲表中选择另一首歌曲时,它必须停止上一首歌曲并播放所选歌曲。
-(void)playOrPauseButtonPressed:(id)sender
{
[self.view addSubview:today_slokaText];
if(playing==NO)
{
[UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
[playButton setBackgroundImage:[UIImage imageNamed:@"Pause.png"] forState:UIControlStateNormal];
[self.view addSubview:today_slokaText];
// Here Pause.png is a image showing Pause Buttomn
NSError *err=nil;
if (!audioPlayer)
{
[self loadSongAtIndex: selectedIndex];
playing=YES;
}
audioPlayer.numberOfLoops = 0;
[audioPlayer prepareToPlay];
[audioPlayer play];
audioPlayer.delegate=self;
if(!audioPlayer.playing)
{
[audioPlayer play];
activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
[self.view addSubview:self.activityIndicator];
self.activityIndicator.center = CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height / 2);
[self.activityIndicator startAnimating];
[playButton setBackgroundImage:[UIImage imageNamed:@"Pause.png"] forState:UIControlStateNormal];
[bg_Image addSubview:activityIndicator];
}
playing=YES;
}
else if (playing==YES)
{
[self.activityIndicator stopAnimating];
self.activityIndicator.alpha=0.0;
// [bg_Image addSubview:activityIndicator];
[playButton setBackgroundImage:[UIImage imageNamed:@"play12.png"] forState:UIControlStateNormal];
[self.view addSubview:today_slokaText];
[audioPlayer pause];
playing=NO;
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateViewForPlayerState) userInfo:nil repeats:YES];
[self.view addSubview:today_slokaText];
}
}
/****************************************** 从服务加载歌曲 *******************************************/
- (void)loadSongAtIndex:(NSInteger) songIndex
{
audioSession=[AVAudioSession sharedInstance];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
urlsArray=[[NSMutableArray alloc]initWithObjects:@"http://01_ARDHANAREESWARASTOTRAM.mp3",@"http://02_AshtaLakshmiStotram.mp3",@"http://03_AYIGIRINANDININANDITHAMEDINI.mp3",, nil];
NSString *sourcePath = [urlsArray objectAtIndex:songIndex];
NSURL *audioURL=[NSURL URLWithString:sourcePath];
NSData *data=[NSData dataWithContentsOfURL:audioURL];
audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:NULL];
audioPlayer.numberOfLoops = 0;
[audioPlayer prepareToPlay];
[audioPlayer play];
audioPlayer.delegate=self;
if(!audioPlayer.playing)
{
[audioPlayer play];
}
if (self.audioPlayer)
{
[self updateViewForPlayerInfo];
[self updateViewForPlayerState];
[self.audioPlayer setDelegate:self];
}
}
【问题讨论】:
标签: ios objective-c iphone avaudioplayer