【问题标题】:i m trying to play mp3 from tableview while user select table row song need to play我正在尝试从 tableview 播放 mp3,而用户选择表格行歌曲需要播放
【发布时间】:2013-04-08 07:45:21
【问题描述】:
//我已经取了 2 首歌曲的数组
nsmutablearray * enrique = [[NSMutableArray alloc]init];
[enrique addObject:@"add.mp3"];
[enrique addObject:@"hero.mp3"];
// this section of uitableview didselectrow
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
cell = [tableView cellForRowAtIndexPath:indexPath];
cellText = cell.textLabel.text;
lbl.text=cellText;
player=[passarray objectAtIndex:indexPath.row];
NSLog(@"mp3 %@",player);
// [passarray indexOfObject:player];
[self.player prepareToPlay];
// [player play];
}
【问题讨论】:
标签:
iphone
uitableview
avfoundation
xcode4.6
【解决方案1】:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[audioPlayer stop];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
songNumber = indexPath.row;
[self loadPlayer:songNumber];
}
-(void)loadPlayer:(int)songIndex
{
if(songIndex <= 0)
{
[previousButton setEnabled:NO];
}
else
{
[previousButton setEnabled:YES];
}
if(songIndex+1 >= self.arySongsList.count)
{
[nextButton setEnabled:NO];
}
else
{
[nextButton setEnabled:YES];
}
if(songIndex < self.arySongsList.count)
{
NSURL *audioFileLocationURL;
audioFileLocationURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@",[self.arySongsList objectAtIndex:songIndex]]];
NSString *str = [[[NSString alloc]initWithFormat:@"%@",audioFileLocationURL]autorelease];
str = [str lastPathComponent];
str = [str stringByReplacingOccurrencesOfString:@"%20" withString:@" "];
str = [str stringByReplacingOccurrencesOfString:@"%5B" withString:@"["];
str = [str stringByReplacingOccurrencesOfString:@"%5D" withString:@"]"];
NSError *error;
if(songIndex == self.arySongsList.count)
{
NSURL *url = [NSURL URLWithString:@"http://sound18.mp3pk.com/pop_remix/ebodf11/ebodf11-15(www.songs.pk).mp3"];
NSData *data = [NSData dataWithContentsOfURL:url];
audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:&error];
}
else
{
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileLocationURL error:&error];
}
[audioPlayer setNumberOfLoops:0];
[audioPlayer setDelegate:self];
if (error)
{
NSLog(@"%@", [error localizedDescription]);
[[self volumeControl] setEnabled:NO];
[[self playPauseButton] setEnabled:NO];
[[self alertLabel] setText:@"Unable to load file"];
[[self alertLabel] setHidden:NO];
}
else
{
[[self alertLabel] setText:[NSString stringWithFormat:@"%@ has loaded", str]];
[[self alertLabel] setHidden:NO];
//Make sure the system follows our playback status
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
//Load the audio into memory
[audioPlayer prepareToPlay];
}
}
if (!self.audioPlayer.playing)
{
[self playAudio];
}
else if (self.audioPlayer.playing)
{
[self pauseAudio];
}
}