10

我目前在我的应用程序中播放背景音乐和其他声音的方式表现得非常奇怪:

  • 关闭背景音乐,播放的其他声音会更大。
  • 开启背景音乐后,声音会小很多。
  • 您甚至可以将音乐调到中音,声音会变得更安静。

最奇怪的部分: 当 iPhone 的音量一直被调低(静音)时,根本就没有声音。在背景音乐打开但没有设备音量的情况下,它可以满足您的预期 - 您听不到音乐或声音效果。但是如果关闭背景音乐,即使设备本身完全关闭,声音效果仍然会播放并且声音很大!

这是我的代码...

对于我的背景音乐:

AVAudioPlayer *musicPlayer;

- (void)playMusic {
    if (musicPlayer == nil) {
        NSURL *musicPath = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"SongFile" ofType:@"mp3"]];
        musicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:musicPath error:nil];
        musicPlayer.volume = 0.2f;
        musicPlayer.numberOfLoops = -1;
    }
    [musicPlayer play];
}

- (void)stopMusic {
    [musicPlayer stop];
}

对于播放过程中的声音:

#import "SoundEffect.h"
SoundEffect *sounds;

- (void)playSoundWithInfo:(NSString *)sound; {
    NSString *path = [[NSBundle mainBundle] pathForResource:sound ofType:@"caf"];
    sounds = nil;
    sounds = [[SoundEffect alloc] initWithContentsOfFile:path];
    [sounds play];
}

任何想法将不胜感激。

4

2 回答 2

1

可能是因为您使用 AVAudioPlayer 播放音乐,使用 SystemSounds 再现音效。为 AVAudioPlayer 设置的音量在应用程序中,但为 SystemSounds 设置的音量是 systemVolume。

于 2011-12-14T03:55:44.690 回答
0

您需要在应用程序中使用和设置AVAudioSession播放前的声音,并且根据您希望音频交互的方式,它有不同的类别。虽然我不知道为什么即使在零音量下音乐仍然会播放,但其他问题似乎来自您不想要的设置。在您的应用程序初始化或开始播放声音的任何地方,请尝试以下代码:AVAudioPlayerMPMediaPlayerAVAudioSessionCategory

[[AVAudioSession sharedInstance] setDelegate:self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive:YES error:nil];

此代码初始化 并将AVAudioSession其设置为声音不会与其他背景声音混合的类别(一旦您激活会话,它们就会停止)并且您的应用程序具有优先权。请注意,屏幕锁定和静音开关仍将允许播放声音(以最大音量)。我相信你可以专门设置它,但我不知道确切的代码。

如果您想要不同的音频行为,请查看您可以在Apple 的 AVAudioSession Class 文档中设置的其他类别。其他选项包括:

AVAudioSessionCategoryAmbient;
AVAudioSessionCategorySoloAmbient;
AVAudioSessionCategoryPlayback;
AVAudioSessionCategoryRecord;
AVAudioSessionCategoryPlayAndRecord;
AVAudioSessionCategoryAudioProcessing;

无论如何,希望音频会话问题导致了这些问题。让我知道这是否有效。

于 2012-01-02T23:41:44.807 回答