如何在 AVAudioplayer 中播放多个文件

Posted

技术标签:

【中文标题】如何在 AVAudioplayer 中播放多个文件【英文标题】:How do I play multiple files in AVAudioplayer 【发布时间】:2013-03-28 09:10:03 【问题描述】:

我在 plist 中有一些歌曲,我想使用 AVAudioplayer 一个接一个地播放它们。 但是当第一首歌结束时,它就停止了。如何从下一首歌曲开始播放器? 我尝试了一个循环,它计算到 plist 中的下一个数字,但它不起作用。玩家在第一轮后停止。这应该很简单,但如何? 这是我的代码的一部分。是否可以像我一样使用循环?

    NSString *soundsPath = [[NSBundle mainBundle] pathForResource:@"soundslist"  
ofType:@"plist"];
soundsList = [[NSArray alloc] initWithContentsOfFile:soundsPath];


 for (int n = 1; n<=5;n++) 
NSString *filename = [soundsList objectAtIndex:n]; //n is number in plist, counting upwards in a for...loop


NSString *path = [[NSBundle mainBundle] pathForResource:filename ofType:@"au"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: path];

 sound = [[AVAudioPlayer alloc] initWithContentsOfURL : fileURL error:nil];

sound.delegate = self;
 

【问题讨论】:

放置 audioPlayerDidFinishPlaying 方法并在该方法中使用增加歌曲的逻辑。 ***.com/questions/8102201/…的可能重复 我尝试将 n++ 放入 audioPlayerDidFinishPlaying 但下次运行它时,它会从头开始。现在我有了我在 viewDidLoad 中编写的代码,对吗?我如何知道 Audioplayer 已停止?我有一个播放按钮,假设歌曲结束时它已经停止?猜猜这里缺少什么 【参考方案1】:

试试这样对你有帮助,

-(void)viewDidLoad

 NSString *soundsPath = [[NSBundle mainBundle] pathForResource:@"soundslist"  
ofType:@"plist"];
soundsList = [[NSArray alloc] initWithContentsOfFile:soundsPath];
[self AddSongToAvplayer];


-(void)AddSongToAvplayer

NSString *filename = [soundsList objectAtIndex:n]; //n is number in plist, counting upwards in a for...loop


NSString *path = [[NSBundle mainBundle] pathForResource:filename ofType:@"au"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: path];

 sound = [[AVAudioPlayer alloc] initWithContentsOfURL : fileURL error:nil];

sound.delegate = self;
n++;


 if(n<=[sound count])
    [NSTimer scheduledTimerWithTimeInterval:sound.duration target:self selector:@selector(AddSongToAvplayer) userInfo:nil repeats:NO];

在上面的代码中,sound.duration 给出了那首特定歌曲的时间间隔,并且基于该歌曲完成后,您可以使用计时器调用该方法。如果最后一首歌曲来了,则停止 NSTimer

编辑:

-(IBAction)AddSongToAvplayer
        if(n<=[sound count])

    NSString *filename = [soundsList objectAtIndex:n]; //n is number in plist, counting upwards in a for...loop


    NSString *path = [[NSBundle mainBundle] pathForResource:filename ofType:@"au"];
    NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: path];

     sound = [[AVAudioPlayer alloc] initWithContentsOfURL : fileURL error:nil];

    sound.delegate = self;
    n++;

    

    

【讨论】:

我试图把它放进去,但似乎我在这里遗漏了一些。根本听不到任何声音。必须检查它是否曾经使用过那段代码。 通过哪种方法获取声音数组。 我在 viewDidLoad 中有一组声音,从 plist 中提取它们。但是按照您的建议将数组放在新位置并没有帮助 谢谢,现在可以了。对数字 n 有一些麻烦。它已通过属性和@synthesize 解决 是的,它运作良好,再次感谢。但我的愿望清单上还有一个是让他们一个接一个地自动播放,而无需任何进一步的用户输入。只需轻按一个按钮即可开始。现在它在第一首之后停止,并且必须再次点击按钮才能获得列表中的下一首歌曲。我在这里做了一些试验,但最终同时播放了所有歌曲。

以上是关于如何在 AVAudioplayer 中播放多个文件的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 AVAudioPlayer 连续播放多个音频文件?

如何用AVAudioPlayer依次播放多个音频文件

如何同时播放多个音频文件

使用 AVAudioPlayer 播放多个音频文件

使用 AVAudioPlayer 播放多个音频文件

如何在 iOS 4 中在后台播放多个音频文件?