2013-02-26 133 views
0

我很困惑如何播放本地歌曲列表。我试图建立一个应用程序,允许用户从列表中选择一首歌曲,然后继续播放他们离开的列表。除非他们选择不同的歌曲,否则它会从该歌曲播放。iOS播放本地音乐列表

我已阅读并尝试了多个关于如何使用AVFoundation播放音频文件的教程,但它们似乎只让我能够播放一种声音。

我已经试过MPMusicPlayer,但是这不起作用,因为我只想播放应用程序附带的文件,而不是从用户的音乐库播放。

这里是我迄今为止从教程:

iPhone Music Player

我都觉得自己和困惑,如何在本地列表播放歌曲。我如何构建这个?

回答

1

在尝试需要此功能的应用程序之前,您应该着眼于使用UITableView

我从记忆写了这个,所以请测试,并确认所有的作品...

确保您的视图控制器实现了从表视图委托方法,并声明UITableView OBJ和像这样的阵列:

@interface YourTableViewController : UIViewController <UITableViewDataSource, UITableViewDelegate> 
{ 
    IBOutlet UITableView *theTableView; 
    NSMutableArray *theArray; 
} 

确保将它们链接到故事板中。您应该看到如上定义的theTableView

当你的应用程序加载,写这个(地方,比如viewDidLoad将被罚款):

theArray = [[NSMutableArray alloc] initWithObjects:@"Item 1", @"Item 2", @"Item 3", nil]; 

你并不需要声明多少章节中有你的表视图,所以现在忽略了这一点,直到后来。但是,您应该申报有多少行是:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [theArray count]; // Return a row for each item in the array 
} 

现在我们需要绘制UITableViewCell。为了简单起见,我们将使用默认的,但您可以轻松制作自己的。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // This ref is used to reuse the cell. 
    NSString *cellIdentifier = @"ACellIdentifier"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 

    if(cell == nil) 
    { 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; 
    } 

    // Set the cell text to the array object text 
    cell.textLabel.text = [theArray objectAtIndex:indexPath.row]; 

    return cell; 
} 

一旦你显示曲目名称的表格,你可以使用的方法:

(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if(indexPath.row == 0) 
    { 
    NSString *arrayItemString = [theArray objectAtIndex:indexPath.row]; 
    // Code to play music goes here... 
    } 
} 

在我们上方宣布NSMutableArray,你不必NSString的添加到阵列。例如,如果要存储多个字符串,则可以创建自己的对象。请记住修改您调用数组项目的位置。

最后,要播放音频,请尝试使用this SO答案。

此外,虽然没有必要,但您可以使用SQLite数据库来存储您希望在列表中播放的曲目,而不是对列表进行硬编码。调用数据库后填写NSMuatableArray

+0

我做了你列出的所有东西,但没有显示在表格视图中。我是否需要链接故事板中的其他内容? – 2013-02-27 15:24:55

+0

您需要将'UITableView'链接到'theTableView',并且您需要在故事板中设置'UITableView'委托('UITableViewDataSource'和'UITableViewDelegate')。 – 2013-02-27 16:15:03