【问题标题】:Pick songs from plist(NSArray) and play using AVAudioPlayer?从 plist(NSArray) 中挑选歌曲并使用 AVAudioPlayer 播放?
【发布时间】:2011-04-20 19:09:39
【问题描述】:

我是一名正在进行编码练习的学生,我很难过!

我的应用程序中有两个 AVAudioPlayer 实例 - 我可以使用直接路径将歌曲加载到每个播放器中,这没问题。

我希望能够在每个播放器上播放多首歌曲。

这可能吗?如果是这样,我该怎么做?

在我的 plist 中,我将键设置为“One.mp3”作为字符串,并将值设置为文件的路径...(在那个部分猜测)。

感谢您的任何见解。

- (void)viewDidLoad {
    [super viewDidLoad];

    //multiple song array

    NSString *soundsPath = [[NSBundle mainBundle] pathForResource:@"soundslist" 
                                                           ofType:@"plist"];

    soundsList = [[NSArray alloc] initWithContentsOfFile:soundsPath];

    NSString* filename = [soundsList objectAtIndex:0];
    NSString *path = [[NSBundle mainBundle] pathForResource:filename 
                                                     ofType:@"mp3"];  

    AVAudioPlayer * newAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] 
                                                                    error:NULL];  
    self.audioPlayer = newAudio; // automatically retain audio and dealloc old file if new file is loaded

    [newAudio release]; // release the audio safely

    audioPlayer.delegate = self; 
    [audioPlayer prepareToPlay];
    [audioPlayer setNumberOfLoops:0];
    [audioPlayer play];
}

【问题讨论】:

    标签: ios audio avaudioplayer


    【解决方案1】:

    听起来您想尝试在一个播放器上播放多首歌曲。如AVAudioPlayer Overview(第 4 个项目符号)所述,这是不可能的。可以使用多个 AVAudioPlayer 播放多首歌曲。像这样的:

    NSMutableArray *audioPlayers = [NSMutableArray arrayWithCapacity:[soundsList count]];
    
    for (NSString *soundPath in soundsList) {
        NSError *error = nil;
    
        AVAudioPlayer *audioPlayer = [AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
        [audioPlayers addObject:audioPlayer];
    
        audioPlayer.delegate = self; 
        [audioPlayer prepareToPlay];
        [audioPlayer setNumberOfLoops:0];
        [audioPlayer play];
    }
    

    我建议您对文件路径进行硬编码,而不是使用 plist 读取它。一旦你得到它的工作,那么你可以尝试使用 plist 阅读它。这样的事情会起作用:

    NSURL *soundURL = [[NSBundle mainBundle] URLForResource:@"One" withExtension:@"mp3"];
    AVAudioPlayer *soundPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:&error]
    

    通过这种方式,您可以消除一层间接性和一个故障点。

    【讨论】:

    • 谢谢达米安,感谢您对此的洞察力,我会试一试...我在这个项目上已经走了好几条路。首先是 MPMusicPlayerController,然后是 AVPlayer,现在是 AVAudioPlayer……很难。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多