我只是想尝试使用MediaPlayer播放声音。下面的代码适用于常规Android项目,通过音频插孔或HDMI监视器的扬声器播放声音。
final MediaPlayer mp = MediaPlayer.create(getActivity(), R.raw.score);
mp.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
});
mp.start();
我接近这个错误的方式吗? MediaPlayer类不能以这种方式使用Android Things吗?
更新1
作为替代方法,我也尝试使用AudioTrack播放声音,这也不起作用:
int i = 0;
byte[] music = null;
InputStream is = getActivity().getResources().openRawResource(R.raw.score);
AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, 44100,
AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT,
AudioTrack.getMinBufferSize(44100,
AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT), AudioTrack.MODE_STREAM);
try{
music = new byte[512];
at.play();
while((i = is.read(music)) != -1)
at.write(music, 0, i);
} catch (IOException e) {
e.printStackTrace();
}
at.stop();
at.release();
更新2
建议设置首选设备。这也行不通。
mAudioOutputDevice = findAudioDevice(AudioManager.GET_DEVICES_OUTPUTS, AudioDeviceInfo.TYPE_BUILTIN_SPEAKER);
获取设备
private AudioDeviceInfo findAudioDevice(int deviceFlag, int deviceType) {
AudioManager manager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
AudioDeviceInfo[] adis = manager.getDevices(deviceFlag);
for (AudioDeviceInfo adi : adis) {
if (adi.getType() == deviceType) {
return adi;
}
}
return null;
}
这里我设置了首选设备。
int i = 0;
byte[] music = null;
InputStream is = getActivity().getResources().openRawResource(R.raw.score);
AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, 44100,
AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT,
AudioTrack.getMinBufferSize(44100,
AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT), AudioTrack.MODE_STREAM);
at.setPreferredDevice(mAudioOutputDevice);
try{
music = new byte[512];
at.play();
while((i = is.read(music)) != -1)
at.write(music, 0, i);
} catch (IOException e) {
e.printStackTrace();
}
at.stop();
at.release();
答案 0 :(得分:1)
我能够使用MediaPlayer类和USB 2.0外部立体声适配器播放声音(如下所示)。只需将适配器连接到Raspberry Pi上的空USB插槽,并将音频输入连接到适配器即可。
final MediaPlayer mp = MediaPlayer.create(getActivity(), R.raw.score);
mp.start();
答案 1 :(得分:0)
您可能需要指定要将声音发送到的音频总线:
private AudioDeviceInfo findAudioDevice(int deviceFlag, int deviceType) {
AudioManager manager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
AudioDeviceInfo[] adis = manager.getDevices(deviceFlag);
for (AudioDeviceInfo adi : adis) {
if (adi.getType() == deviceType) {
return adi;
}
}
return null;
}
然后找到音频插孔总线:
mAudioInputDevice = findAudioDevice(AudioManager.GET_DEVICES_INPUTS, AudioDeviceInfo.TYPE_BUILTIN_MIC);
mAudioOutputDevice = findAudioDevice(AudioManager.GET_DEVICES_OUTPUTS, AudioDeviceInfo.TYPE_BUILTIN_SPEAKER);
然后您可以运行audioTrack.setPreferredDevice(mAudioOutputDevice);