使用 SoundPool 播放声音
我需要在我的应用程序中播放短声音。我编写了以下代码,但我的三星手机没有声音并且出现奇怪的振动。但与此同时,这段代码在我的 Android 模拟器上运行良好。我的代码是:
package com.samplers;
import android.app.Activity;
import android.media.SoundPool;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class FixVibroActivity extends Activity {
/** Called when the activity is first created. */
private Button white;
private SoundPool spool;
private int soundID;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
spool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
soundID = spool.load(this, R.raw.error, 1);
white = (Button)findViewById(R.id.whiteBtn);
white.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Sound();
}
});
}
public void Sound(){
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
float volume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
spool.play(soundID, volume, volume, 1, 0, 1f);
};
}
请帮我解决这个问题!先感谢您! :)
I need to play a short sound in my application. I wrote the following code but I have no sound and strange vibration appeared on my Samsung phone. But in the same time this code works well on my android simulator. My code is:
package com.samplers;
import android.app.Activity;
import android.media.SoundPool;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class FixVibroActivity extends Activity {
/** Called when the activity is first created. */
private Button white;
private SoundPool spool;
private int soundID;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
spool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
soundID = spool.load(this, R.raw.error, 1);
white = (Button)findViewById(R.id.whiteBtn);
white.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Sound();
}
});
}
public void Sound(){
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
float volume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
spool.play(soundID, volume, volume, 1, 0, 1f);
};
}
Help me to solve this problem, please! Thank you in advance! :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的音量控制或声音文件播放可能存在问题:如果您将
Sound()
函数更改为此,它会做什么?如果您的手机无法正确处理 R.raw.error 文件格式,但模拟器可以正确处理,那将非常奇怪。There might either be an issue with your volume control or with your sound file playing correctly: if you change the
Sound()
function to this what does it do? If your phone is not correctly handling theR.raw.error
file format but the emulator is doing it correctly that would be VERY strange.