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

后端 未结 4 1086
余生分开走
余生分开走 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:23

    Instead of AVAudioPlayer you can use AVQueuePlayer which suits this use case better as suggested by Ken. Here is a bit of code you can use:

    @interface AVSound : NSObject 
    
    @property (nonatomic, retain) AVQueuePlayer* queuePlayer;
    
    - (void)addToPlaylist:(NSString*)pathForResource ofType:(NSString*)ofType;
    - (void)playQueue;
    
    @end
    
    @implementation AVSound
    - (void)addToPlaylist:(NSString*)pathForResource ofType:(NSString*)ofType
    {
        // Path to the audio file
        NSString *path = [[NSBundle mainBundle] pathForResource:pathForResource ofType:ofType];
    
        // If we can access the file...
        if ([[NSFileManager defaultManager] fileExistsAtPath:path])
        {
    
            AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL fileURLWithPath:path]];
    
            if (_queuePlayer == nil) {
                _queuePlayer = [[AVQueuePlayer alloc] initWithPlayerItem:item];
            }else{
                [_queuePlayer insertItem:item afterItem:nil];
            }
        }
    
    }
    
    
    - (void)playQueue
    {
        [_queuePlayer play];
    }
    @end
    

    Then to use it: In your interface file:

    @property (strong, nonatomic) AVSound *pageSound;
    

    In your implementation file:

    - (void)addAudio:(Book*)book pageNum:(int)pageNum
    {
    
        NSString *soundFileEven = [NSString stringWithFormat:@"%02d", pageNum-1];
        NSString *soundPathEven = [NSString stringWithFormat:@"%@_%@", book.productId,     soundFileEven];
        NSString *soundFileOdd = [NSString stringWithFormat:@"%02d", pageNum];
        NSString *soundPathOdd = [NSString stringWithFormat:@"%@_%@", book.productId, soundFileOdd];
    
        if (_pageSound == nil) {
            _pageSound = [[AVSound alloc]init];
            _pageSound.player.volume = 0.5;
        }
    
        [_pageSound clearQueue];
    
        [_pageSound addToPlaylist:soundPathEven ofType:@"mp3"];
        [_pageSound addToPlaylist:soundPathOdd ofType:@"mp3"];
        [_pageSound playQueue];
    }
    

    HTH

提交回复
热议问题