Я хочу играть несколько MP3-файлов, последовательно (один за другим), используя AVAudioPlayer. Я попробовал это, и он останавливается после воспроизведения первого MP3. Однако, если я иду в отладчик, он отлично работает .. любые идеи? Я где-то читал AVAudioPlayer играет аудио в фоновом режиме .. Как предотвратить это делать это? Vas
AVAudioPlayer - играть несколько звуковых файлов в последовательности
Я думаю , что AVQueuePlayer(подкласс AVPlayer) делает именно эту работу (играет последовательность элементов) , так прошивка 4.1:
http://developer.apple.com/library/ios/#documentation/AVFoundation/Reference/AVQueuePlayer_Class/Reference/Reference.html
Я не пробовал это сам, однако, но, безусловно, дать попробовать ему.
Ну, ваш пример кода не работает из коробки для меня. Тааак, я решил ответить с фиксированной версией:
Looper.h:
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
@interface Looper : NSObject <AVAudioPlayerDelegate> {
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
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 * looper = [[Looper alloc] initWithFileNameQueue:[NSArray arrayWithObjects: audioFile, audioFile2, nil ]];
Я только чуть более года опыта с развитием iPhone / IPad с помощью Objective-C, так не стесняйтесь ответить с дополнительной критики.
Используйте один AVAudioPlayer за звук.
Это хорошая идея, чтобы инициализировать, подготовить детали, и в очереди впереди времени, например, по методу viewDidLoad.
Если вы работаете на Swift,
override func viewDidLoad() {
super.viewDidLoad()
let item0 = AVPlayerItem.init(URL: NSBundle.mainBundle().URLForResource("url", withExtension: "wav")!)
let item1 = AVPlayerItem.init(URL: NSBundle.mainBundle().URLForResource("dog", withExtension: "aifc")!)
let item2 = AVPlayerItem.init(URL: NSBundle.mainBundle().URLForResource("GreatJob", withExtension: "wav")!)
let itemsToPlay:[AVPlayerItem] = [item0, item1, item2]
queuePlayer = AVQueuePlayer.init(items: itemsToPlay)
}
а затем, когда происходит событие,
queuePlayer.play()
Обратите внимание, что если вы используете очередь, вы все еще можете иметь некоторые пробела между звуками.
Вы можете найти версию Objective-C в вопросе Как сделать что - то , когда AVQueuePlayer заканчивает последний playeritem
Надеюсь, поможет.
Я реализовал класс справиться с этим.
Для того, чтобы использовать просто сделать что-то вроде этого:
[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 <Foundation/Foundation.h>
@interface Looper : NSObject <AVAudioPlayerDelegate> {
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













