我正在制作一个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];
您的UPDATE代码将创建player
为局部变量,当方法(在其中调用此代码)返回时,该变量将超出范围。
一旦player
超出范围,它就会被释放,并且音频甚至没有机会开始播放。
您需要在retain
某个地方玩:
@property AVAudioPlayer* player;
...
- (void)initializePlayer
{
NSString *scanSoundPath = [[NSBundle mainBundle] pathForResource:@"beep"
ofType:@"caf"];
NSURL *scanSoundURL = [NSURL fileURLWithPath:scanSoundPath];
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:scanSoundURL
error:nil];
self.player.volume = 0.5;
}
然后在其他地方打电话:
[self.player play];
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句