5

我知道这是一个已经被问过很多次的问题,并且我已经检查了 SO 中相关的大部分答案,但是我没有运气找到我的问题的正确答案。

这是问题所在:

当某些事件被触发时,我尝试在游戏中播放 mp3 文件(最多 2 秒),我使用 AudioPlayer 这样做,下面是代码块:

NSError *error;
AVAudioPlayer *audioPlayer = [[[AVAudioPlayer alloc] initWithContentsOfURL:[[NSBundle mainBundle] URLForResource: @"ding" withExtension: @"mp3"] error:&error] autorelease];
if (error)  {
    NSLog(@"Error creating audio player: %@", [error userInfo]);
}
else {
    BOOL success = [audioPlayer play];
    // This always is "Play sound succeeded"
    NSLog(@"Play sound %@", success ? @"succeeded" : @"failed");
}

当我在 iPhone 4s、iTouch 3/4 中运行此代码时,声音始终播放得很好且清晰,但在 iPad 1 或 iPad2 中,扬声器没有声音。但是当我插入耳机时,奇怪的事情发生了,我的耳机有声音!iPad 未处于静音模式且 URL 正确。

我很困惑为什么会这样。

PS:我尝试了以下代码(从HERE获得)来输出音频输出端口类型:

CFDictionaryRef asCFType = nil;
UInt32 dataSize = sizeof(asCFType);
AudioSessionGetProperty(kAudioSessionProperty_AudioRouteDescription, &dataSize, &asCFType);
NSDictionary *easyPeasy = (NSDictionary *)asCFType;
NSDictionary *firstOutput = (NSDictionary *)[[easyPeasy valueForKey:@"RouteDetailedDescription_Outputs"] objectAtIndex:0];
NSString *portType = (NSString *)[firstOutput valueForKey:@"RouteDetailedDescription_PortType"];
NSLog(@"first output port type is: %@!", portType);

当我插入耳机时,输出是“第一个输出端口类型是耳机!” 当我拔掉它时,输出竟然是“第一个输出端口类型是扬声器!”

如果有人可以提供一些帮助或建议,那就太好了。

4

3 回答 3

5

对此有一个代码更改解决方案,但也有一个最终用户解决方案:将“响铃/静音开关”打开。AVAudioSessionCategorySoloAmbient具体来说,问题在于如果手机处于静音模式 ,AVAudioSessions 的默认设置是静音。

如原始海报所述,您可以通过调用来覆盖此行为:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

AVAudioSession Reference建议设置AVAudioSessionCategoryPlayback类别:

用于播放录制的音乐或其他对成功使用应用至关重要的声音。

于 2014-05-20T22:47:33.033 回答
3

要使用 Swift 2 语法更新上面的@JonBrooks 答案,我将以下内容放入我的 viewDidLoad() 以覆盖静音开关并播放我的声音:

do {

    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)

} catch let error as NSError {

    print(error)
}
于 2015-11-04T23:25:44.507 回答
0

找到解决方案!我在播放前添加了这行代码后,声音终于从扬声器中播放出来了

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

我现在仍然不明白为什么,我会深入研究它。:)

于 2012-12-11T01:58:39.277 回答