AVQueuePlayer仅在第一次单击按钮时播放一次声音序列

时间:2013-09-07 20:57:48

标签: ios avqueueplayer

我在AVQueuePlayer方法中设置了一个viewDidLoad指定播放器。我还有一个UIbutton方法来播放该序列。

这是我的观点做了加载方法

AVPlayerItem *firstSound = [[AVPlayerItem alloc] initWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"first" ofType:@"mp3"]]];
AVPlayerItem *secondSound = [[AVPlayerItem alloc] initWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"second" ofType:@"mp3"]]];
AVPlayerItem *thirdSound = [[AVPlayerItem alloc] initWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"third" ofType:@"mp3"]]];

player = [AVQueuePlayer queuePlayerWithItems:[NSArray arrayWithObjects:firstSound, secondSound, thirdSound,  nil]];

这是我按钮的方法

-(IBAction)sequencePlay:(id)sender {[player play];}

按下按钮仅在首次加载视图时产生一次声音序列。当我再次点击按钮时没有任何反应。但是,如果我导航到另一个视图控制器并返回到此视图控制器,它将在我第一次再次按下按钮时工作,但与以前一样,它仅适用于第一次点击。

更新: 根据第一个解决问题的答案,在按钮而不是viewDidLoad方法中进行设置是关键。

我的mp3文件很小,每个文件只说一个字。我有一个带有3列的UIPickerView设置,根据选择的行,当按下按钮时,它将按顺序播放这些特定的单词。关于我如何实现这一目标的任何好建议?

我目前正在尝试这样做,但收到错误

-(IBAction)sequencePlay:(id)sender 
{
NSString *sayFirst = _firstRowWord.description;

AVPlayerItem *firstSound = [[AVPlayerItem alloc] initWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:sayFirst.description ofType:@"mp3"]]];

我收到以下错误 *由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'* - [NSURL initFileURLWithPath:]:nil string parameter'

firstRowWord的描述与我想播放的mp3文件的名称相同

1 个答案:

答案 0 :(得分:2)

您可以尝试使用sequencePlay:方法在那里设置AVQueuePlayer。 所以:

-(IBAction)sequencePlay:(id)sender {
AVPlayerItem *firstSound = [[AVPlayerItem alloc] initWithURL:[NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource:@"first" ofType:@"mp3"]]];
AVPlayerItem *secondSound = [[AVPlayerItem alloc] initWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"second" ofType:@"mp3"]]];
AVPlayerItem *thirdSound = [[AVPlayerItem alloc] initWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"third" ofType:@"mp3"]]];

player = [AVQueuePlayer queuePlayerWithItems:[NSArray arrayWithObjects:firstSound, secondSound, thirdSound,  nil]];
[player play];
}

如果您担心这种性能,可以使用actionAtItemEnd属性重新填充播放器。 希望这有帮助!