【发布时间】:2013-11-19 05:40:41
【问题描述】:
我正在尝试同时为 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 check 进行初始化,但没有收到任何错误:
NSError *sessionError = nil;
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:outputFileURL error:&sessionError];
if (sessionError)
{
NSLog(@"Error in audioPlayer: %@",[sessionError localizedDescription]);
}
解决方案
我的NSMutableArrays 的初始化似乎有问题。
我将它们更改为:
self.soundsCreated = [[NSMutableArray alloc]init];
self.playerArray = [[NSMutableArray alloc]init];
到
self.soundsCreated = [NSMutableArray new];
self.playerArray = [NSMutableArray new];
然后解决了它
【问题讨论】:
标签: ios iphone objective-c avaudioplayer