如何通过本地代码使用JNI在Android上获取音频音量? [英] How to get audio volume on Android using JNI from native code?

查看:227
本文介绍了如何通过本地代码使用JNI在Android上获取音频音量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用C ++的JNI在Android上获取音频音量.我的约束是我无权访问Java部件.

I'm trying to get the audio volume on Android using JNI from C++. My constraint is that I don't have any access to the Java part.

我找到了一种从此站点进行JNI查询的方法:

I found a way to make my JNI query from this site: AudioManager.cpp

但是我想我对这段代码中的最后一次调用有误:

but I supposed I did something wrong with my last call in this code:

jclass AudioManager = env->FindClass("android/media/AudioManager");

jmethodID getStreamVolume = env->GetMethodID(AudioManager, "getStreamVolume", "()I");

jint stream = 3; //STREAM_MUSIC
int volume = env->CallIntMethod(AudioManager, getStreamVolume, stream); //Crash here

在此代码中,我试图从Android文档中由id = 3标识的STREAM_MUSIC获取音频音量:

In this code, I'm trying to get the audio volume from STREAM_MUSIC identified by id=3 in the Android documentation: http://developer.android.com/reference/android/media/AudioManager.html#getStreamVolume(int)

jclass context = env->FindClass("android/content/Context");

jfieldID audioServiceField = env->GetStaticFieldID(context, "AUDIO_SERVICE", "Ljava/lang/String;");

jstring jstr = (jstring)env->GetStaticObjectField(context, audioServiceField);

jmethodID getSystemServiceID = env->GetMethodID(context, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;");

jobject tm = env->CallObjectMethod(currentAndroidActivity, getSystemServiceID, jstr);

jclass AudioManager = env->FindClass("android/media/AudioManager");

jmethodID getStreamVolume = env->GetMethodID(AudioManager, "getStreamVolume", "(I)I");

jint stream = 3; //MUSIC_STREAM = 3
int volume = env->CallIntMethod(tm, getStreamVolume, stream);
DEBUG_LOG(DEBUG_TAG, "volume = " + to_string(volume));

推荐答案

您需要AudioManager的实例才能调用该方法.要获取实例,可以使用context.getSystemService(Context.AUDIO_SERVICE)(根据链接到的文档).

You need an instance of AudioManager to call that method. To get the instance, you can use context.getSystemService(Context.AUDIO_SERVICE) (as per documentation you linked to).

您链接到的AudioManager.cpp实际上并不读取流体积值,而只是读取静态STREAM_MUSIC字段的值,因此不需要AudioManager的实例.

The AudioManager.cpp you linked to doesn't actually read the stream volume value, just the value of the static STREAM_MUSIC field and therefore doesn't need an instance of AudioManager.

在这里获取AudioManager实例的主要问题实际上是,您需要一个Context实例,通常是您的ActivityServiceApplication.

The main problem in getting an instance of AudioManager here is really that to do that you need a Context instance, which is usually your Activity, Service or Application.

这篇关于如何通过本地代码使用JNI在Android上获取音频音量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆