Thay vì AVAudioPlayer, bạn có thể sử dụng AVQueuePlayer phù hợp với trường hợp sử dụng này tốt hơn theo đề xuất của Ken. Dưới đây là một chút mã bạn có thể sử dụng:
@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
Sau đó, để sử dụng nó: Trong tập tin giao diện của bạn:
@property (strong, nonatomic) AVSound *pageSound;
Trong tập tin thực thi của bạn:
- (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
Nguồn
2014-07-08 08:59:35
Rất khó để tìm thấy bất kỳ thông tin nào về việc này ... – dot