java - 模拟器无法播放声音

标签 java android android-studio button audio

我在“原始”文件中设置了声音。然而,当我把所有东西放在一起时,模拟器上的原始点击声音正在播放,但我的“鼠标点击”声音却没有。

我将鼠标点击声音设置为“sound1”。

声音只有1秒长,我不知道这是否重要。

Activity 主

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Activity1" />

    <ImageButton
        android:id="@+id/Special_Button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/transparent"
        android:src="@drawable/button_images"
        android:onClick="playSound"/>

</LinearLayout>

主要 Activity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        AudioAttributes audioAttributes = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_ASSISTANCE_SONIFICATION)
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .build();

        soundPool = new SoundPool.Builder()
                .setMaxStreams(1)
                .setAudioAttributes(audioAttributes)
                .build();


    } else {
        soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC,
                0);
    }

    sound1 = soundPool.load(this, R.raw.sound1, 1);

    button = findViewById(R.id.Special_Button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            openActivity2();
        }
    });

}

public void openActivity2() {
    Intent intent = new Intent(this, Activity2.class);
    startActivity(intent);
}

public void playSound(View v) {
    soundPool.play(R.raw.sound1, 1,1,0
    ,0,1);
}

@Override
protected void onDestroy() {
    super.onDestroy();

    soundPool.release();
    soundPool = null;
}
}

最佳答案

看起来您已经在 XML 中实现了 onClick ,并在 Java 中实现了 setOnClickListener

据我所知,您的代码正在运行 onClickListener,它正在启动 openActivity2() 方法,并跳过 playSound() 方法。

尝试删除 XML 中的 onClick 并将 playSound() 集成到 setOnClickListener 中。

您还可以添加 AudioFocus 请求。 此代码有效:在我的例子中,我使用了 fragment 类,但这可以在任何 Activity 中使用。

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;



public class fragment1 extends Fragment {

    //These are the declarations

    Button btn;

    MediaPlayer mMediaPlayer;

    private AudioManager mAudioManager;

    //This tells the media player what to do if AudioFocus is changed
    private AudioManager.OnAudioFocusChangeListener 
       mOnAudioFocusChangeListener =
        new AudioManager.OnAudioFocusChangeListener() {
            @Override
            public void onAudioFocusChange(int focusChange) {

                if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT ||
                        focusChange ==   AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK){

                    mMediaPlayer.pause();
                    mMediaPlayer.seekTo(0);
                } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN){
                    mMediaPlayer.start();
                }else if (focusChange == AudioManager.AUDIOFOCUS_LOSS){
                    releaseMediaPlayer();
                }
            }
        };

//This tells the media player what to do when the playback is done
private MediaPlayer.OnCompletionListener mOnCompletionListener = new MediaPlayer.OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer mp) {
        releaseMediaPlayer();
    }
};

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view =  inflater.inflate(R.layout.**YOUR LAYOUT HERE**,container,false);

    //This assigns the audio manager to this view 
    mAudioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);

    btn = view.findViewById(R.id.btn);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            /* First calls the releaseMediaPlayer() method to make sure there
             * are no other instances of the media player that exist. 
             */
            releaseMediaPlayer();

            //This requests the AudioFocus
            int result = mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener,
                    AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);

            //This if statement deals with the above request
            if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED){
                mMediaPlayer = MediaPlayer.create(getActivity(), **YOUR MEDIA RESOURCE HERE**);
                mMediaPlayer.start();

                mMediaPlayer.setOnCompletionListener(mOnCompletionListener);
            }
        }
    });


    return view;
}

//This tells the media player to stop if the app is closed
@Override
public void onStop(){
    super.onStop();
    releaseMediaPlayer();
}

//This method is to release the instance of the media player
private void releaseMediaPlayer(){

    if (mMediaPlayer != null){

            mMediaPlayer.release();
            mMediaPlayer = null;
            mAudioManager.abandonAudioFocus(mOnAudioFocusChangeListener);
      }
   }
}

关于java - 模拟器无法播放声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59744497/

相关文章:

java - 使用java或kotlin在libs中搜索aar文件名

java - 如何将div元素转换为图像

Java 对非英语正则表达式的支持

android - 如何确定在 OpenGL ES 2 中纹理上传是否成功?

Android 和 Phonegap : Intent to launch an other Application

android-studio - Android studio 编译问题(gradle task : compileDebugJavaWithJavac)

java - 无法使用android.support.v7.widget.Toolbar

android - 迁移到 Androidx 后程序类型已经存在 : com. google.common.util.concurrent.ListenableFuture

java - ConcurrentModificationException 在 android 中为每个抛出

android - 如何在 Android 中根据区域设置和设备屏幕指定单个图像