【问题标题】:How to play more than two songs using AVAudioPlayer如何使用 AVAudioPlayer 播放两首以上的歌曲
【发布时间】:2012-03-20 15:25:11
【问题描述】:

我想在我的应用中播放两首以上的歌曲。如何使用 AVAudioPlayer 做到这一点?

【问题讨论】:

  • 你想同时播放还是不同时间播放?歌曲是什么格式的?
  • 我想一首一首播放。当一首歌曲播放完毕后,它会自动开始另一首歌曲。我将所有歌曲存储在一个项目目录中。

标签: iphone


【解决方案1】:

我打算输入答案,但谷歌提供了一个非常好的答案:

http://www.iphonedevsdk.com/forum/iphone-sdk-development/27285-play-sequence-audio-files-avaudioplayer.html

页面的第一段代码将按顺序调用所有声音:

- (void)playSoundSequence { 

    // Make array containing audio file names 
    NSArray  *theSoundArray = [NSArray arrayWithObjects:@"one",@"two",nil];

    int totalSoundsInQueue = [theSoundArray count];

    for (int i=0; i < totalSoundsInQueue; i) {

        NSString *sound = [theSoundArray objectAtIndex:i];

                // Wait until the audio player is not playing anything
        while(![audioPlayer isPlaying]){

            AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] 
                                                pathForResource:sound ofType:@"wav"]] error:NULL];
            self.audioPlayer = player;
            [player release];
            [audioPlayer setVolume:1.0f];
            [audioPlayer play];
            //Increment for loop counter & move onto next iteration
                        i++;      
        }
    }

}

但是,使用 AVAudioPlayerDelegate 可能会更好:

如果你不想在循环中等待,你也可以让你的 控制器一个 AVAudioPlayerDelegate 并实现

代码:

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag

这将在到达音频文件末尾时调用,在 从哪一点开始播放下一个音频文件。 audioPlayerDidFinishPlaying 将在那个时候再次被调用 播放完,然后你开始下一个,等等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多