我正在尝试同时播放AVAudioPlayer的几个声音文件。我在@AVAudioPlayer Help: Playing multiple sounds simultaneously, stopping them all at once, and working around Automatic Reference Counting上读了一个解释如何做的线程。当我尝试一次仅播放一个文件(self.options.on为ON)时,这似乎是一个奇怪的问题,但是当我尝试创建多个实例(else语句)却不播放它们时,这似乎是一个奇怪的问题。播放。我检查了输出文件URL是否正确,这是什么,所以它不起作用的原因是什么?
谢谢!
- (void)playTapped:(id)sender
{
if (!recorder.recording)
{
if(self.options.on)
{
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
NSArray *pathComponents = [NSArray arrayWithObjects:
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],
[NSString stringWithFormat:@"sound%i.m4a",last],
nil];
NSURL *outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:outputFileURL error:nil];
NSLog(@"%@",player.url);
[player setDelegate:self];
[player play];
}
else
{
// trying to play all sounds at once
for (NSString *str in self.soundsCreated){
NSLog(@"%@",str);
NSArray *pathComponents = [NSArray arrayWithObjects:
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],
[NSString stringWithFormat:@"sound%@.m4a",str],
nil];
NSURL *outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:outputFileURL error:nil];
NSLog(@"%@",audioPlayer.url);
[audioPlayer prepareToPlay];
[audioPlayer setDelegate:self];
[audioPlayer play];
}
}
}
}
注意
我尝试使用
NSError
检查进行初始化,但未收到任何错误:NSError *sessionError = nil;
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:outputFileURL error:&sessionError];
if (sessionError)
{
NSLog(@"Error in audioPlayer: %@",[sessionError localizedDescription]);
}
解决方案
我的
NSMutableArray
的初始化似乎是一个问题。我将它们从:
self.soundsCreated = [[NSMutableArray alloc]init];
self.playerArray = [[NSMutableArray alloc]init];
至
self.soundsCreated = [NSMutableArray new];
self.playerArray = [NSMutableArray new];
然后修复它
最佳答案
播放小文件时,我也面临着相同的情况:
这是我的解决方案(示例)
- (void)dropSoundWhileRefresh
{
NSError *sessionError = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&sessionError];
[[AVAudioSession sharedInstance] setActive:YES error:&sessionError];
[[AVAudioSession sharedInstance] setDelegate:self];
NSURL *musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"waterDrops" ofType:@"mp3"]];
dropSound = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:nil];
[dropSound setDelegate:self];
[dropSound setVolume:0.10];
[dropSound setNumberOfLoops:0];
[dropSound play];
}
关于ios - AVAudioPlayer无法同时播放声音,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20064041/