连接耳机时如何强制从 iPhone 扬声器发出音频?

发布于 2024-10-17 17:13:28 字数 128 浏览 0 评论 0原文

我正在尝试向我的 iPhone 应用程序之一添加扬声器功能。我已经创建了录音功能,但是当我播放录制的音频时,它仅播放到手机耳机。

我需要的是在扬声器上播放录制的文件,即使连接了耳机也是如此。我怎样才能重新路由音频来做到这一点?

I'm trying to add a loudspeaker feature to one of my iPhone apps. I already created the recording functionality, but when I play the recorded audio it only plays to the phone headset.

What I need is the recorded file to be played on the loudspeaker, even if there is a headset attached. How could I reroute the audio to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

十六岁半 2024-10-24 17:13:28

您需要使用 AudioSessionSetProperty 覆盖默认音频属性。看看类似这样的东西,强制所有音频都进入扬声器(请注意,如果插入耳机,甚至会发生这种情况)。

OSStatus err = 0;
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
err = AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute,sizeof(audioRouteOverride),&audioRouteOverride);

要检测耳机,请尝试以下操作(这实际上是从另一篇 SO 帖子中复制/粘贴代码,所以买者自负,但它对我有用):

/**
 * Tells us if the headset is plugged in
 */
- (BOOL) headsetIsPluggedIn
{
  BOOL returnVal = NO;

  UInt32 routeSize = sizeof(CFStringRef);
  CFStringRef route = NULL;
  OSStatus error = AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &routeSize, &route);
  if (!error && (route != NULL) && ([(NSString*)route rangeOfString:@"Head"].location != NSNotFound))
  {
    CFRelease(route);
    returnVal = YES;
  }
  return returnVal;
}

编辑:关于 CFRelease 是否合适的评论。有铁杆核心基金会专家愿意参与进来吗?

You need to override the default audio properties using AudioSessionSetProperty. Look at something like this to force all audio to go to the speaker (note that this will even happen if headphones are plugged in).

OSStatus err = 0;
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
err = AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute,sizeof(audioRouteOverride),&audioRouteOverride);

To detect the headphones, try this (this is literally copy/paste code off of another SO post, so caveat emptor, but it works for me):

/**
 * Tells us if the headset is plugged in
 */
- (BOOL) headsetIsPluggedIn
{
  BOOL returnVal = NO;

  UInt32 routeSize = sizeof(CFStringRef);
  CFStringRef route = NULL;
  OSStatus error = AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &routeSize, &route);
  if (!error && (route != NULL) && ([(NSString*)route rangeOfString:@"Head"].location != NSNotFound))
  {
    CFRelease(route);
    returnVal = YES;
  }
  return returnVal;
}

EDIT: There is a bit of a discussion in the comments about whether the CFRelease is appropriate or not. Any hardcore Core Foundation experts care to weigh in?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文