声音在意图加载时没有响起

时间:2014-10-28 06:46:16

标签: android audio android-intent soundpool

我正在使用意图从另一个类调用此类,我想在课程的负载上播放这首歌“song.ogg”..请帮帮我怎么做?

public class DetlsActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detls_layout);

        getActionBar().setDisplayHomeAsUpEnabled(true);

        SoundPool soundPool;
        int soundID;
        soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
        soundID = soundPool.load(this,R.raw.song, 1);
        AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        //soundPool.play(soundID,1f,1f,1,0,1f);
        Toast.makeText(this,"Ringing Song",Toast.LENGTH_LONG).show();
        try {
        AssetFileDescriptor assetFileDescriptor = this.getAssets().openFd("song.ogg");
        soundPool.load(assetFileDescriptor,1);
            Toast.makeText(this,"Played",Toast.LENGTH_LONG).show();
        }
        catch (Exception e) {
            Log.d("LOGCAT","Exception Song");
        }

1 个答案:

答案 0 :(得分:0)

    SoundPool soundPool;
    int soundID;
    soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
    Toast.makeText(this,"Ringing Song",Toast.LENGTH_LONG).show();
    try {
        soundID = soundPool.load(this,R.raw.song, 1);
        int waitLimit = 1000;
        int waitCounter = 0;
        int throttle = 10;
        while(soundPool.play(soundID, 1.f, 1.f, 1, 0, 1.f) == 0 && waitCounter < waitLimit)
          {waitCounter++; SystemClock.sleep(throttle);}
        Toast.makeText(this,"Played "+soundID,Toast.LENGTH_LONG).show();

    }
    catch (Exception e) {
        Log.d("LOGCAT","Exception Song");
        Toast.makeText(this,"Exception "+e,Toast.LENGTH_LONG).show();
    }

用上面的代码替换您的代码。当前代码发出警告 soundpool示例1未准备好因此请使用while条件进行检查。

此处,您的资源位于原始文件夹中,这就是我们使用soundID = soundPool.load(this,R.raw.song, 1);的原因。如果您的资源当时位于资源文件夹中,则可以使用soundID = soundPool.load(getAssets().openFd("song.ogg"),1);