首页 文章

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

提问于
浏览
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);

当我插入耳机时,输出为 "first output port type is headphone!" ,当我拔掉它时,输出结果是 "first output port type is speaker!"

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

3 回答

  • 5

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

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

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

    AVAudioSession Reference建议设置 AVAudioSessionCategoryPlayback 类别:

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

  • 3

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

    do {
    
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
    
    } catch let error as NSError {
    
        print(error)
    }
    
  • 0

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

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

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

相关问题