AVAudioPlayer - playing multiple audio files, in sequence

后端 未结 5 807
忘了有多久
忘了有多久 2020-12-16 06:14

I want to play multiple MP3 files, in sequence (one after the other) , using AVAudioPlayer. I tried it, and it stops after playing the first MP3. However, if I go into deb

5条回答
  •  轮回少年
    2020-12-16 06:29

    I've implemented a class to handle this.

    To use just do something like this:

    [looper playAudioFiles:[NSArray arrayWithObjects:
        @"add.mp3",
        [NSString stringWithFormat:@"%d.mp3", numeral1.tag],
        @"and.mp3",
        [NSString stringWithFormat:@"%d.mp3", numeral2.tag],
        nil
    ]];
    

    Looper.m

    #import "Looper.h"
    @implementation Looper
    @synthesize player, fileNameQueue;
    
    - (id)initWithFileNameQueue:(NSArray*)queue {
        if ((self = [super init])) {
            self.fileNameQueue = queue;
            index = 0;
            [self play:index];
        }
        return self;
    }
    
    - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
        if (index < fileNameQueue.count) {
            [self play:index];
        } else {
            //reached end of queue
        }
    }
    
    - (void)play:(int)i {
        self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:[[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle] pathForResource:[fileNameQueue objectAtIndex:i] ofType:nil]] error:nil];
        [player release];
        player.delegate = self;
        [player prepareToPlay];
        [player play];    
        index++;
    }
    
    - (void)stop {
        if (self.player.playing) [player stop];
    }
    
    - (void)dealloc {
        self.fileNameQueue = nil;
        self.player = nil;        
        [super dealloc];
    }
    
    @end
    

    Looper.h

    #import 
    
    
    @interface Looper : NSObject  {
        AVAudioPlayer* player;
        NSArray* fileNameQueue;
        int index;
    }
    
    @property (nonatomic, retain) AVAudioPlayer* player;
    @property (nonatomic, retain) NSArray* fileNameQueue;
    
    - (id)initWithFileNameQueue:(NSArray*)queue;
    - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag;
    - (void)play:(int)i;
    - (void)stop;
    
    
    @end
    

提交回复
热议问题