简体   繁体   English

如何在不干扰程序UI的情况下播放声音?

[英]How do I play a sound without any interference with the UI of my program?

my app aims to play some sound rhythmically following some mathematical formulas. 我的应用旨在按照一些数学公式有节奏地播放声音。 In other version of this program developed for other platform I just "sleep" the thread the time needed until I need to play the next sound but in android, if you sleep the process the UI sleeps as well. 在为其他平台开发的该程序的其他版本中,我只是“休眠”线程所需的时间,直到我需要播放下一个声音为止,但是在android中,如果您休眠了进程,则UI也会休眠。 I try the next code as an example, trying to separate the UI and the sound process: 我以下一个代码为例,尝试将UI和声音过程分开:

public class SoundThread extends Thread{
private MediaPlayer player;
SoundThread(Context context)
{
    player = MediaPlayer.create(context, R.raw.ex);
}
public void run()
{
    for(int x=0;x<100;x++)
    {
        player.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

This class starts mediaplayer with an example sound and the context of the activity that is calling it and it is supposed to play R.raw.ex every second. 此类以示例声音和调用该声音的活动的上下文开始mediaplayer,并且应该每秒播放一次R.raw.ex。 But when I call it from my activity I hear that the sound plays correctly but my device consider that the app is frozen. 但是当我从活动中调用它时,我听到声音可以正确播放,但是我的设备认为该应用程序已冻结。

Thank you very much. 非常感谢你。

For this particular application, if you don't need playback control, you can just wrap that bit of code up in an AsyncTask . 对于此特定应用程序,如果不需要播放控制,则只需将这段代码包装在AsyncTask中

If you want to be able to control playback, then you should implement a Service . 如果您希望能够控制播放,则应该实现Service

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM