0

这个想法是单击微调器并让它给你一个播放声音的时间列表。一旦你选择一个声音并点击它应该播放的按钮。它不起作用,我不知道为什么。我有一个主屏幕和一个主 Activity,当您单击一个按钮时,它会带您进入一个新的 Activity 和一个新的布局。我可以加载新的布局和新的活动,这是下面的特色,但声音和微调器没有启动。

package com.androidsleepmachine.gamble;

package com.androidsleepmachine.gamble;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View; 
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

public class Ship extends Activity implements View.OnClickListener {
public static final int[] TIME_IN_MINUTES = { 30, 45, 60 };
public MediaPlayer mediaPlayer;
public Handler handler = new Handler();
public Button button1;
public Spinner spinner1;

// Initialize the activity
@Override
public void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    setContentView(R.layout.ship);

    button1 = (Button) findViewById(R.id.btnSubmit);
    button1.setOnClickListener(this);
    spinner1 = (Spinner) findViewById(R.id.spinner1);
    ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this,   
            android.R.layout.simple_spinner_item);
}

// Play the sound and start the timer
private void playSound(int resourceId) {
    // Cleanup any previous sound files
    cleanup();
    // Create a new media player instance and start it
    mediaPlayer = MediaPlayer.create(this, resourceId);
    mediaPlayer.start();
    // Create the timer to stop the sound after x number of milliseconds
    int selectedTime = TIME_IN_MINUTES[spinner1.getSelectedItemPosition()];
    handler.postDelayed(runnable, selectedTime * 60 * 1000);
}

// Handle button callbacks
@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btnSubmit:
            playSound(R.raw.ocean_ship);
            break;
    }
}

// Stop the sound and cleanup the media player
public void cleanup() {
    if (mediaPlayer != null) {
        mediaPlayer.stop();
        mediaPlayer.release();
        mediaPlayer = null;
    }
    // Cancel any previously running tasks
    handler.removeCallbacks(runnable);
}

// Runnable task used by the handler to stop the sound
public Runnable runnable = new Runnable() {
    public void run() {
        cleanup();
    }
};

}

4

2 回答 2

1

看起来问题出在您的switch陈述中。您正在检查idofbutton1但您分配给的唯一按钮listenerbutton1具有idof btnSubmit。所以你的playSound()函数永远不会被调用。

改变你onClick()

    // Handle button callbacks
@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btnSubmit:
            playSound(R.raw.ocean_ship);
            break;
    }
}

编辑

为了您的ArrayAdapter尝试,例如

ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this,  android.R.layout.simple_spinner_item, TIME_IN_MINUTES);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);          
spinner1.setAdapter(adapter); 
于 2013-09-16T15:29:01.870 回答
0

你是在模拟器上做的吗?Mediaplayer 在模拟器上不起作用。您必须在真实设备中进行测试。

于 2013-09-16T15:28:54.900 回答