声音不能在iPad扬声器上播放,但在耳机和iPod Touch / iPhone扬声器上工作正常

时间:2012-12-11 01:41:38

标签: ios ipad avaudioplayer

我知道这个问题已被多次提出,我已经检查了大部分相关的答案,但我没有找到解决问题的正确答案。

问题在于:

当某个事件被触发时,我试图在游戏中播放一个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);

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

有人可以提供一些帮助或建议会很棒。

3 个答案:

答案 0 :(得分:5)

有一个代码更改解决方案,但也是一个最终用户解决方案:转动' Ring / Silent开关'继续。具体来说,问题是如果手机处于静音模式,AVAudioSessions的默认设置AVAudioSessionCategorySoloAmbient将保持静音。

正如原始海报所述,您可以通过调用:

来覆盖此行为
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

AVAudioSession Reference建议设置AVAudioSessionCategoryPlayback类别:

  

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

答案 1 :(得分:3)

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

do {

    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)

} catch let error as NSError {

    print(error)
}

答案 2 :(得分:0)

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

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

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

相关问题