【问题标题】:iOS Play list of music back locallyiOS 本地播放音乐列表
【发布时间】:2013-02-26 22:25:26
【问题描述】:

我对如何在本地播放歌曲列表感到困惑。我正在尝试构建一个应用程序,允许用户从列表中选择一首歌曲,然后继续播放他们离开的列表。除非他们选择不同的歌曲,否则它会从该歌曲开始播放。

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

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

这是我到目前为止从该教程获得的内容:

我对如何在本地播放列表中的歌曲感到困惑和困惑。我该如何构建它?

【问题讨论】:

    标签: iphone ios xcode avaudioplayer


    【解决方案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 answer中的答案。

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

    【讨论】:

    • 我完成了您列出的所有操作,但表格视图中没有显示任何内容。我需要在情节提要中链接其他任何内容吗?
    • 您需要将UITableView 链接到theTableView,并且您需要在情节提要中设置UITableView 代表(UITableViewDataSourceUITableViewDelegate)。
    猜你喜欢
    • 1970-01-01
    • 2012-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-26
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多