我正在使用AVAudioPlayer
在触发方法时播放MP3文件。
这很好用但我现在想添加一个能够选择从列表触发方法时播放哪个音频文件,这不是很好。
我创建了一个UISegmentedControl
,并尝试更改AVAudioPlayer
方法以反映已选择的内容但是我现在在应用启动时收到以下错误:
' NSInvalidArgumentException',原因:' *** - [NSURL initFileURLWithPath:]:nil string参数'
根据我的理解,我收到上述错误,因为当AVAudioPlayer
尝试initWithContentsOfUrl:
时,被引用的字符串还没有包含任何数据,我认为它可能来自UISegmentedController
中的默认段,但情况并非如此。
我已经为此搜索了一个解决方案,但找不到任何与我想要实现的内容相匹配的内容,我能找到的最接近的是为我想播放的每个音频文件启动AVAudioPlayer
的新会话然而,这似乎很长,最终可能仍然不起作用。
以下是我的代码到目前为止,如果您可以建议我如何使这项工作,我将不胜感激。
代表UISegmentedController
:
- (void) selectTone:(id)sender
{
if (self.alarmToneType == 0) {
self.filePath = [[NSBundle mainBundle] pathForResource: @"alarm" ofType: @"mp3"];
NSLog(@"Tone Selected 0 %@", [HRASettingsViewController alarmToneDescription:(int) self.alarmToneType]);
}
if (self.alarmToneType == 1) {
self.filePath = [[NSBundle mainBundle] pathForResource: @"redalert" ofType: @"mp3"];
NSLog(@"Tone Selected 1 %@", [HRASettingsViewController alarmToneDescription:(int) self.alarmToneType]);
}
if (self.alarmToneType == 2) {
self.filePath = [[NSBundle mainBundle] pathForResource: @"greenalaert" ofType: @"mp3"];
NSLog(@"Tone Selected 2 %@", [HRASettingsViewController alarmToneDescription:(int) self.alarmToneType]);
}
}
我已经将字符串创建为@property,但并不认为你需要它。
代表AVAudioPlayer
:
- (void) setupAppAudio {
/////////////////////////////////////////////////////////////////////////////////////
// SOUNDS
// Registers this class as the delegate of the audio session.
[[AVAudioSession sharedInstance] setActive:YES error:nil];
// Use this code instead to allow the app sound to continue to play when the screen is locked.
NSError *sessionError = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &sessionError];
if (sessionError) {
NSLog(@"AVAudioSession ERROR %@", sessionError);
} else {
NSLog(@"AVAudioSession SUCCESSFUL");
}
// Tell other music to be quiet when we are talking!
UInt32 doSetProperty = 1;
AudioSessionSetProperty (kAudioSessionProperty_OtherMixableAudioShouldDuck,
sizeof (doSetProperty),
&doSetProperty);
// Registers the audio route change listener callback function
AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange,
audioRouteChangeListenerCallback,
(__bridge void *)(self));
NSError *activationError = nil;
[[AVAudioSession sharedInstance] setActive: YES error: &activationError];
// setup
//NSString *filePath;
AVAudioPlayer *newPlayer;
newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: [NSURL fileURLWithPath:self.filePath] error: nil];
self.beepPlayer = newPlayer;
// "Preparing to play" attaches to the audio hardware and ensures that playback
// starts quickly when the user taps Play
[self.beepPlayer prepareToPlay];
[self.beepPlayer setVolume: 1.0];
[self.beepPlayer setDelegate: self];
}