2

我正在制作一个 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];
4

3 回答 3

3

您的 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];
于 2016-06-09T06:41:56.167 回答
2

从“播放 UI 声音效果或使用系统声音服务调用振动”下的多媒体编程指南:

此外,当您使用 AudioServicesPlaySystemSound 函数时:

  • 声音以当前系统音量播放,没有可用的程序音量控制

因此,根据 Apple Docs,这似乎是不可能的。但是这个AVAudioPlayer类允许你通过它的volume属性来做到这一点。

在您当前的代码中,您所要做的就是添加

AVAudioPlayer *newPlayer = 
        [[AVAudioPlayer alloc] initWithContentsOfURL: scanSoundURL
                                               error: nil];
[newPlayer play];
于 2015-01-02T23:45:25.897 回答
0

目标 C

使用系统音量播放声音

@interface UIViewController () {
    AVAudioPlayer *audioPlayer;
}

-(void) PlayCoinSound {
//#import <AVFoundation/AVFoundation.h>
    NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"CoinSound" ofType:@"mp3"];
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:soundPath] error: nil];
    audioPlayer.volume = 1.0;
    [audioPlayer prepareToPlay];
    [audioPlayer play];
}

播放完整的声音

- (void)PlayWithFullVolume {
    //#import <AudioToolbox/AudioToolbox.h>
    SystemSoundID soundID;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath: soundPath], &soundID);
    AudioServicesPlaySystemSound (soundID);

}
于 2018-02-16T14:35:01.373 回答