2013-02-26 136 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