How to play multiple audio files in a row with AVAudioPlayer?

后端 未结 4 1088
余生分开走
余生分开走 2020-12-14 05:09

I have 5 songs in my app that I would like to play one after the other with AVAudioPlayer.

Are there any examples of this? How can I accomplish this?

Any ex

4条回答
  •  悲&欢浪女
    2020-12-14 05:24

    For every song you want to make make a single AVPlayer.

    NSURL *url = [NSURL URLWithString:pathToYourFile];
    AVPlayer *audioPlayer = [[AVPlayer alloc] initWithURL:url];
    [audioPlayer play];

    You can get a Notification when the player ends. Check AVPlayerItemDidPlayToEndTimeNotification when setting up the player:

      audioPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone; 
    
      [[NSNotificationCenter defaultCenter] addObserver:self
                                               selector:@selector(playerItemDidReachEnd:)
                                                   name:AVPlayerItemDidPlayToEndTimeNotification
                                                 object:[audioPlayer currentItem]];
    

    this will prevent the player to pause at the end.

    in the notification:

    - (void)playerItemDidReachEnd:(NSNotification *)notification
    {
        // start your next song here
    }
    

    You can start your next song as soon as you get a notification that the current playing song is done. Maintain some counter which is persistent across selector calls. That way using counter % [songs count] will give you an infinite looping playlist :)

    Don't forget un unregister the notification when releasing the player.

提交回复
热议问题