【发布时间】:2020-06-03 04:33:23
【问题描述】:
当我尝试在我的应用程序中启动声音时,它不会播放。我已经看到该方法确实被调用了,但是 soundPool 只是不想播放声音。该应用程序按预期启动,但是,它只是不想播放排队的声音。是我做错了什么吗?我要播放的音乐文件是否太大? (35.4MB)
感谢任何输入!
StartActivity(相关位)
public class StartActivity extends AppCompatActivity {
private Button startButton;
//Sounds
private SoundManager soundManager;
private int ambient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_activity);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
startButton = (Button) findViewById(R.id.startButton);
//Setting Up sounds
soundManager = new SoundManager(this);
ambient = soundManager.getSoundID(R.raw.music_ambient);
soundManager.playLoop(ambient);
Application.setSoundManager(soundManager);
应用
public class Application {
public static SoundManager soundManager;
public static SoundManager getSoundManager() {
return soundManager;
}
public static void setSoundManager(SoundManager soundManagerIns) {
soundManager = soundManagerIns;
}
}
SoundManager 类
import android.content.Context;
import android.media.SoundPool;
import android.util.Log;
public class SoundManager {
private Context context;
private SoundPool soundPool;
private boolean isPlaying = false;
SoundManager(Context context) {
this.context = context;
SoundPool.Builder builder = new SoundPool.Builder();
builder.setMaxStreams(10);
soundPool = builder.build();
}
int getSoundID(int resourcesID) {
return (soundPool.load(context, resourcesID, 1));
}
void play(int soundId) {
soundPool.play(soundId, 1, 1, 1, 0, 1);
}
void playLoop(int soundId){
if(!isPlaying) {
Log.d("LEADER", "called this");
soundPool.play(soundId, 1, 1, 1, -1, 1);
isPlaying = true;
}
}
void stop(int soundId){
isPlaying = false;
soundPool.stop(soundId);
}
}
【问题讨论】:
-
为什么你的应用程序中有
soundManager?它基本上是一个全局可变变量,由于几个原因,这可能不是一个好主意,例如如果你不小心的话线程安全,以及推理什么可以在何时何地修改。我会考虑重构它,尽管我可能错了。 -
您是否采用了现有的有声音的 Android 示例应用程序并尝试让它成功运行?这可以帮助减少可能的原因并帮助您找到错误。
-
您的程序中是否有任何部分“拥有”资源
SoundManager?考虑“所有权”对于管理资源非常有用,尤其是因为它为何时应该释放给定资源提供了指导。例如,如果您拥有由给定活动拥有的资源,那么初始化和释放该资源作为特定活动生命周期的一部分可能是有意义的。在 Android 中,Context在实践中通常与所有权相关。