java - 放弃音频焦点并继续之前的音乐/视频流

标签 java android audio text-to-speech

我在我的应用程序中实现了 TTS(文本转语音)功能。一切都很顺利,但现在我遇到了一个无法找到解决方案的问题。

基本上,我在激活 TTS 功能之前获得音频焦点。在实际的应用程序中,当我这样做时音乐就会停止(这正是我希望它的行为方式)。然而,一旦 TTS 功能完成,我就放弃了音频焦点,音乐/视频也不再继续。我不知道如何继续在 TTS 之前播放的音乐/视频流。

这是我实现的代码:

TTS 完成后放弃音频焦点的代码:

@Override
public void onUtteranceCompleted(String s) {
    Log.v(TAG, s);
    if(!getUserPreference().getTest()){
        //setDefaultVolume();
        audioManager.abandonAudioFocus(this);
    }
}

在 TTS 开始之前获取音频焦点的代码:

audioManager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);

int requestAudioFocusResult = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
if(requestAudioFocusResult == AudioManager.AUDIOFOCUS_REQUEST_GRANTED){...

欢迎就我的问题提出任何进一步的问题。期待答案/建议。

根据答案更改:

int requestAudioFocusResult = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);

我已经按照答案所述实现了,但是 requestAudioFocusResult 值返回为 1,而它应该是 3。有什么想法吗?

最佳答案

once the TTS function is finished, I abandon the audio focus and the music/video doesn't continue.

由于您无限期地请求音频焦点 (AUDIOFOCUS_GAIN),因此您描述的行为听起来像 the expected behavior :

[I]t’s assumed that another application is now being used to listen to audio and your app should effectively end itself. In practical terms, that means stopping playback, removing media button listeners—allowing the new audio player to exclusively handle those events—and abandoning your audio focus. At that point, you would expect a user action (pressing play in your app) to be required before you resume playing audio.

<小时/>

在我看来,您应该请求临时音频焦点,即 AudioManager.AUDIOFOCUS_GAIN_TRANSIENT (或 AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_CAN_DUCK ,具体取决于您认为其他音频焦点是否可以音频以较低的音量在后台继续播放)。

关于java - 放弃音频焦点并继续之前的音乐/视频流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52727054/

相关文章:

javascript - 通过 html 音频标签在移动浏览器上播放音频

html - Scirra是如何在Construct 2中获得如此完美的HTML5音频的?

java - 解压 zip 文件时出错

java - Hibernate slqjdbc4 列带空格

java - 无法将变量添加到我的数组

php - 在PHP中上传文件到服务器错误

Java-填充重叠的多边形

java - 如何在 Knife.fromHtml() 中留出空格、转到下一行、下划线或将字符加粗?\n、\t、\r 没有任何效果

android - 数据库调用使 Android 应用程序崩溃

android - 使用 Apportable 时可以在 xcode 中安装 Android 设备模拟器吗