同时播放/暂停/停止多个音频文件以及顺序方式

时间:2016-04-27 12:22:30

标签: ios objective-c audio sequential simultaneous

我正在从事音乐应用, 想要同时播放多个音频文件, 找到了许多stackoverflow链接来获得解决方案,但我的方案仍然没有运气,

我有8个数组,每个数组都有一些音频文件名。 喜欢,

array1 = @[@"aud1",@"aud2"];
array2 = @[@"aud4",@"aud5",@"aud8",@"aud11"];
....
array8 = @[@"aud3",@"aud6",@"aud7"];

所有音频文件都存储在我的项目中,文件扩展名为.wav。

现在,我想要实现的是,所有阵列都应该以顺序方式播放,同时播放一个阵列中的所有音频文件。即aud1,aud2 (array1)应该一起播放,然后按顺序方式立即播放aud4,aud5,aud8,aud11 (array2)应该同时播放等等。

我也想实现暂停/停止功能。 我知道AVAudioPlayerAVQueuePlayer ..

AVQueuePlayer适用于顺序播放。我已经实现了这段代码,Play/Pause/Stop multiple audio file which are stored locally但它不能用于同时播放,然后顺序播放。

感谢任何帮助!

提前致谢!

2 个答案:

答案 0 :(得分:1)

@Gati,你试过GCD - Grand Central Dispatch吗?我认为这可能是解决问题的方法。

NSArray *array = @[@"aud1",@"aud2"];
    for (id obj in array) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

            // Play each aud here
            NSLog(@"%@",obj);

        });
    }

Apple参考:https://developer.apple.com/library/ios/documentation/Performance/Reference/GCD_libdispatch_Ref/

请查看以下内容:https://www.raywenderlich.com/60749/grand-central-dispatch-in-depth-part-1

答案 1 :(得分:1)

Player * play = [[Looper alloc] initWithFileNameQueue:[NSArray arrayWithObjects: audioFile, audioFile2, nil ]];

Player.h

#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>

@interface Player : NSObject <AVAudioPlayerDelegate> {
    AVAudioPlayer* play;
    NSArray* fileNameQueue;
    int index;
}

@property (nonatomic, retain) AVAudioPlayer* play;
@property (nonatomic, retain) NSArray* fileNameQueue;

- (id)initWithFileNameQueue:(NSArray*)queue;
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)play successfully:(BOOL)flag;
- (void)play:(int)i;
- (void)stop;

@end

Player.m

#import "Player.h"
@implementation Play
@synthesize player, fileNameQueue;

- (id)initWithFileNameQueue:(NSArray*)queue {
    if ((self = [super init])) {
        self.fileNameQueue = queue;
        index = 0;
        [self play:index];
    }
    return self;
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)play 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];
    play.delegate = self;
    [play prepareToPlay];
    [play play];    
    index++;
}

- (void)stop {
    if (self.play.playing) [play stop];
}


@end