ios - AVQueuePlayer 第一次点击按钮时只播放一次我的声音序列

标签 ios avqueueplayer

我在 viewDidLoad 方法中设置了一个名为 AVQueuePlayer 的播放器。我还有一个播放该序列的 UIbutton 方法。

这是我的 View 加载方法

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];}

第一次加载 View 时,按下按钮只会产生一次声音序列。当我再次单击按钮时,没有任何反应。然而,如果我导航到另一个 View Controller 并返回到这个 View Controller ,它会在我第一次再次按下按钮时起作用,但和以前一样,它只对第一次点击起作用。

更新: 根据第一个答案,在按钮而不是 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文件完全相同

最佳答案

您可以尝试使用 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 属性重新填充播放器。 希望这对您有所帮助!

关于ios - AVQueuePlayer 第一次点击按钮时只播放一次我的声音序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18677854/

相关文章:

ios - Google Consent SDK - 链接器错误

ios - 在UIWebView中加载PDF并出现错误DiskImageCache:无法解析旧目录的绝对路径

ios - iOS 4 或 r5 可以在后台更新/更改播放项目吗?

ios - 控制 avqueueplayer 中项目的预缓冲

ios - AVPlayer "freezes"开始缓冲音频流的应用程序

iphone - AVQueuePlayer无法播放声音

iphone - 如何检测文件名中的中文/日文字符?

ios - 将文本标签设置为时间间隔的差异

ios - 无法验证 MYAPP.app 的代码签名

ios - AVURLAsset loadValuesAsynchronously 从不失败