我正在创建一个基于的应用程序在这里说话示例应用程序。如果耳机已插入或默认通过扬声器播放,我希望音频通过耳机播放。
我使用了底部的代码来实现这一点,并且除非在播放过程中拔掉耳机,否则它工作正常。此时播放结束,没关系。问题是,当我再次点击播放时,播放变得很奇怪,并且停止按钮停止工作。它还从停止的地方开始播放,而不是像通常按下停止按钮时那样从头开始重置。
同样,如果在应用程序打开之前插入耳机,也会导致奇怪的行为。
也许我需要抓住“耳机拔出”事件并让它“按下停止按钮”?因为现在的做法是不正确的。
用简单的形式提出我的问题:如何正确设置 iPhone 上的核心音频以通过扬声器和耳机播放。
任何可以解决这个问题的代码都会有很大的帮助。谢谢!
OSStatus error = AudioSessionInitialize(NULL, NULL, NULL, NULL);
if (error) printf("ERROR INITIALIZING AUDIO SESSION! %d\n", error);
else
{
UInt32 category = kAudioSessionCategory_PlayAndRecord;
// UInt32 category = kAudioSessionCategory_MediaPlayback;
error = AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(category), &category);
if (error) printf("couldn't set audio category!");
// It is bugs when I unplug the headphones!
UInt32 doChangeDefaultRoute = 1;
AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof (doChangeDefaultRoute), &doChangeDefaultRoute);
error = AudioSessionAddPropertyListener(kAudioSessionProperty_AudioRouteChange, propListener, self);
if (error) printf("ERROR ADDING AUDIO SESSION PROP LISTENER! %d\n", error);
UInt32 inputAvailable = 0;
UInt32 size = sizeof(inputAvailable);
// we do not want to allow recording if input is not available
error = AudioSessionGetProperty(kAudioSessionProperty_AudioInputAvailable, &size, &inputAvailable);
if (error) printf("ERROR GETTING INPUT AVAILABILITY! %d\n", error);
btn_record.enabled = (inputAvailable) ? YES : NO;
// we also need to listen to see if input availability changes
error = AudioSessionAddPropertyListener(kAudioSessionProperty_AudioInputAvailable, propListener, self);
if (error) printf("ERROR ADDING AUDIO SESSION PROP LISTENER! %d\n", error);
error = AudioSessionSetActive(true);
if (error) printf("AudioSessionSetActive (true) failed");