我正在制作 iOS 8 Objective-C 应用程序(部署在我的 iPhone 5 上),我正在使用此代码通过手机从应用程序播放声音:
@property (assign) SystemSoundID scanSoundID;
...
- (void)someFunction {
...
//Play beep sound.
NSString *scanSoundPath = [[NSBundle mainBundle]
pathForResource:@"beep" ofType:@"caf"];
NSURL *scanSoundURL = [NSURL fileURLWithPath:scanSoundPath];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)scanSoundURL, &_scanSoundID);
AudioServicesPlaySystemSound(self.scanSoundID);
...
}
这段代码工作正常,但 beep.caf 声音非常响亮。我希望以 50%的音量播放哔声(不改变 iPhone 的音量)。换句话说,我不想触摸 iPhone 的实际音量,我只想播放幅度较小的声音。
我怎样才能做到这一点(最好是我现在正在使用的音频服务)?
更新
在试图实现路易斯的答案之后,这段代码没有播放任何音频(即使我的手机没有静音且我的音量调高了):
NSString *scanSoundPath = [[NSBundle mainBundle] pathForResource:@"beep"
ofType:@"caf"];
NSURL *scanSoundURL = [NSURL fileURLWithPath:scanSoundPath];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:scanSoundURL
error:nil];
player.volume = 0.5;
[player play];
3 回答
您的 UPDATE 代码创建
player
作为局部变量,当方法(您在其中调用此代码)返回时,该变量将超出范围。一旦
player
超出范围,它就会被释放,音频甚至没有机会开始播放。你需要在某个地方
retain
玩家:然后在你打电话的其他地方:
从“播放 UI 声音效果或使用系统声音服务调用振动”下的多媒体编程指南:
因此,根据 Apple Docs,似乎不可能。但是
AVAudioPlayer
类允许你通过它的volume
属性来实现。在您当前的代码中,您所要做的就是添加
目标 C.
播放系统音量
播放全音