开发者

Play sound with SoundPool

开发者 https://www.devze.com 2023-03-14 01:06 出处:网络
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 andro

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 i开发者_开发问答s:

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! :)


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 the R.raw.error file format but the emulator is doing it correctly that would be VERY strange.

public void Sound(){
        AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        float volume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        android.util.Log.v("SOUND","["+volume+"]["+spool.play(soundID, volume, volume, 1, 0, 1f)+"]");
    };
0

精彩评论

暂无评论...
验证码 换一张
取 消