I have I think simple problem which I can't fix on my own. In the code below I need to set the loudBars variable to the other class. I made the setLoudBars() but it just doesn't work. Anyone sees any solution in this?
public class DrumActivity extends Activity {
private final short minBpm = 40;
private final short maxBpm = 208;
private short bpm = 100;
private short noteValue = 4;
private short beats = 4;
private short volume;
private short initialVolume;
private double beatSound = 2440;
private double sound = 6440;
private AudioManager audio;
private MetronomeAsyncTask metroTask;
private Button plusButton;
private Button minusButton;
private TextView currentBeat;
private Handler mHandler;
private int loudBars = 2;
private short silentBars = 1;
// have in mind that: http://stackoverflow.com/questions/11407943/this-handler-class-should-be-static-or-leaks-might-occur-incominghandler
// in this case we should be fine as no delayed messages are queued
private Handler getHandler() {
return new Handler() {
#Override
public void handleMessage(Message msg) {
String message = (String)msg.obj;
if(message.equals("1")) {
currentBeat.setTextColor(Color.GREEN);
}else {
currentBeat.setTextColor(getResources().getColor(R.color.yellow));
}
currentBeat.setText(message);
}
};
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drum);
metroTask = new MetronomeAsyncTask();
/* Set values and listeners to buttons and stuff */
TextView eLoudBars = (TextView) findViewById(R.id.eLoudBars);
eLoudBars.setText(""+loudBars);
TextView eSilentBars = (TextView) findViewById(R.id.eSilentBars);
Button minusLoud = (Button) findViewById(R.id.lbminus);
minusLoud.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loudBars--;
if(loudBars < 1)
loudBars = 1;
TextView eLoudBars = (TextView) findViewById(R.id.eLoudBars);
eLoudBars.setText(""+loudBars);
metroTask.setLoudBars(loudBars);
}
});
Button plusLoud = (Button) findViewById(R.id.lbplus);
plusLoud.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loudBars++;
TextView eLoudBars = (TextView) findViewById(R.id.eLoudBars);
eLoudBars.setText(""+loudBars);
metroTask.setLoudBars(loudBars);
}
});
Button minusSilent = (Button) findViewById(R.id.sbminus);
Button plusSilent = (Button) findViewById(R.id.sbplus);
TextView bpmText = (TextView) findViewById(R.id.bps);
bpmText.setText(""+bpm);
TextView timeSignatureText = (TextView) findViewById(R.id.timesignature);
timeSignatureText.setText(""+beats+"/"+noteValue);
plusButton = (Button) findViewById(R.id.plus);
plusButton.setOnLongClickListener(plusListener);
minusButton = (Button) findViewById(R.id.minus);
minusButton.setOnLongClickListener(minusListener);
currentBeat = (TextView) findViewById(R.id.currentBeat);
currentBeat.setTextColor(Color.GREEN);
Spinner beatSpinner = (Spinner) findViewById(R.id.beatspinner);
ArrayAdapter<Beats> arrayBeats =
new ArrayAdapter<Beats>(this,
android.R.layout.simple_spinner_item, Beats.values());
beatSpinner.setAdapter(arrayBeats);
beatSpinner.setSelection(Beats.four.ordinal());
arrayBeats.setDropDownViewResource(R.layout.spinner_dropdown);
beatSpinner.setOnItemSelectedListener(beatsSpinnerListener);
Spinner noteValuesdSpinner = (Spinner) findViewById(R.id.notespinner);
ArrayAdapter<NoteValues> noteValues =
new ArrayAdapter<NoteValues>(this,
android.R.layout.simple_spinner_item, NoteValues.values());
noteValuesdSpinner.setAdapter(noteValues);
noteValues.setDropDownViewResource(R.layout.spinner_dropdown);
noteValuesdSpinner.setOnItemSelectedListener(noteValueSpinnerListener);
audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
initialVolume = (short) audio.getStreamVolume(AudioManager.STREAM_MUSIC);
volume = initialVolume;
SeekBar volumebar = (SeekBar) findViewById(R.id.volumebar);
volumebar.setMax(audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumebar.setProgress(volume);
volumebar.setOnSeekBarChangeListener(volumeListener);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public synchronized void onStartStopClick(View view) {
Button button = (Button) view;
String buttonText = button.getText().toString();
if(buttonText.equalsIgnoreCase("start")) {
button.setText(R.string.stop);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
metroTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
else
metroTask.execute();
} else {
button.setText(R.string.start);
metroTask.stop();
metroTask = new MetronomeAsyncTask();
Runtime.getRuntime().gc();
}
}
private void maxBpmGuard() {
if(bpm >= maxBpm) {
plusButton.setEnabled(false);
plusButton.setPressed(false);
} else if(!minusButton.isEnabled() && bpm>minBpm) {
minusButton.setEnabled(true);
}
}
public void onPlusClick(View view) {
bpm++;
TextView bpmText = (TextView) findViewById(R.id.bps);
bpmText.setText(""+bpm);
metroTask.setBpm(bpm);
maxBpmGuard();
}
private OnLongClickListener plusListener = new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
bpm+=20;
if(bpm >= maxBpm)
bpm = maxBpm;
TextView bpmText = (TextView) findViewById(R.id.bps);
bpmText.setText(""+bpm);
metroTask.setBpm(bpm);
maxBpmGuard();
return true;
}
};
private void minBpmGuard() {
if(bpm <= minBpm) {
minusButton.setEnabled(false);
minusButton.setPressed(false);
} else if(!plusButton.isEnabled() && bpm<maxBpm) {
plusButton.setEnabled(true);
}
}
public void onMinusClick(View view) {
bpm--;
TextView bpmText = (TextView) findViewById(R.id.bps);
bpmText.setText(""+bpm);
metroTask.setBpm(bpm);
minBpmGuard();
}
private OnLongClickListener minusListener = new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
bpm-=20;
if(bpm <= minBpm)
bpm = minBpm;
TextView bpmText = (TextView) findViewById(R.id.bps);
bpmText.setText(""+bpm);
metroTask.setBpm(bpm);
minBpmGuard();
return true;
}
};
private OnSeekBarChangeListener volumeListener = new OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
volume = (short) progress;
audio.setStreamVolume(AudioManager.STREAM_MUSIC, progress, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
};
private OnItemSelectedListener beatsSpinnerListener = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Beats beat = (Beats) arg0.getItemAtPosition(arg2);
TextView timeSignature = (TextView) findViewById(R.id.timesignature);
timeSignature.setText(""+beat+"/"+noteValue);
metroTask.setBeat(beat.getNum());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
private OnItemSelectedListener noteValueSpinnerListener = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
NoteValues noteValue = (NoteValues) arg0.getItemAtPosition(arg2);
TextView timeSignature = (TextView) findViewById(R.id.timesignature);
timeSignature.setText(""+beats+"/"+noteValue);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
#Override
public boolean onKeyUp(int keycode, KeyEvent e) {
SeekBar volumebar = (SeekBar) findViewById(R.id.volumebar);
volume = (short) audio.getStreamVolume(AudioManager.STREAM_MUSIC);
switch(keycode) {
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_DOWN:
volumebar.setProgress(volume);
break;
}
return super.onKeyUp(keycode, e);
}
public void onBackPressed() {
metroTask.stop();
// metroTask = new MetronomeAsyncTask();
Runtime.getRuntime().gc();
audio.setStreamVolume(AudioManager.STREAM_MUSIC, initialVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
finish();
}
private class MetronomeAsyncTask extends AsyncTask<Void,Void,String> {
Metronome metronome;
MetronomeAsyncTask() {
mHandler = getHandler();
metronome = new Metronome(mHandler);
}
protected String doInBackground(Void... params) {
metronome.setBeat(beats);
metronome.setNoteValue(noteValue);
metronome.setBpm(bpm);
metronome.setBeatSound(beatSound);
metronome.setSound(sound);
metronome.setLoudBars(loudBars);
metronome.play();
return null;
}
public void stop() {
metronome.stop();
metronome = null;
}
public void setBpm(short bpm) {
metronome.setBpm(bpm);
metronome.calcSilence();
}
public void setBeat(short beat) {
if(metronome != null)
metronome.setBeat(beat);
}
public void setLoudBars(int loudBars) {
if(metronome != null)
metronome.setLoudBars(loudBars);
}
}
}
Related
I am trying to add a toggle button, so that my image button switches the direction that it translates based on the status of the toggle button. However, I am running into problems when trying to add it to the media player, and when using the if statement.
public class MainActivity extends AppCompatActivity {
TextToSpeech tts1;
ToggleButton toggleButton;
public void changeTranslation(View view){
boolean on = ((ToggleButton)view).isChecked();
if(on){
toggleButton.setText("Speech-to-Farts");
Toast.makeText(getApplicationContext(),"Translating speech to farts.",Toast.LENGTH_SHORT);
} else{
toggleButton.setText("Farts-to-Speech");
Toast.makeText(getApplicationContext(),"Translating farts to speech.",Toast.LENGTH_SHORT);
}
}
private static final String TAG = "MainActivity";
private MediaPlayer mMediaPlayer;
private MediaPlayer.OnCompletionListener mCompletionListener = new MediaPlayer.OnCompletionListener(){
#Override
public void onCompletion(MediaPlayer mediaPlayer){
releaseMediaPlayer();
}
};
private void releaseMediaPlayer(){
if(mMediaPlayer != null){
mMediaPlayer.release();
mMediaPlayer=null;
}
}
TextView tv1;
ImageButton b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(textView);
b1 = (ImageButton) findViewById(R.id.recordButton);
final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggle_button);
toggleButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (toggleButton.isChecked()) {
toggleButton.setText("Farts-to-Speech");
} else {
toggleButton.setText("Speech-to-Farts");
}
}
});
tts1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
tts1.setLanguage(Locale.US);
}
}
});
b1.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onClick(View v) {
int[] fartLibrary={};
String[] speechLibrary={};
if(toggleButton==true) {
releaseMediaPlayer();
String randomTranslation = (speechLibrary[new Random().nextInt(speechLibrary.length)]);
tts1.speak(randomTranslation, TextToSpeech.QUEUE_FLUSH, null);
} else {
releaseMediaPlayer();
mMediaPlayer=MediaPlayer.create(this,fartLibrary);
mMediaPlayer.start();
mMediaPlayer.setOnCompletionListener(mCompletionListener);
}
}
});
}
}
This is my Translations.java. I'm not sure if this is necessary anymore though
public class Translations{
private String mSpeechTranslation;
private int mFartTranslation;
public Translations(String speechTranslation, int fartTranslation){
mFartTranslation = fartTranslation;
mSpeechTranslation = speechTranslation;
}
public String getmSpeechTranslation(){ return mSpeechTranslation;}
public int getmFartTranslation(){ return mFartTranslation;}
}
I am trying to create a music player in ViewPager when the user swipes, the player should play the next song. The views are updating correctly but the song is not sync with them. For example, it's playing the second song in the first fragment. I tried a lot of things but I'm not able to find where is the issue. Please anyone give me a solution. Thanks in advance.
public class AudioActivity extends AppCompatActivity {
List<PlayerModel> audioList;
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio);
audioList=getIntent().getParcelableArrayListExtra(getString(R.string.SONG_LIST));
position=getIntent().getIntExtra(getString(R.string.SONG_POSITION),0);
final ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
}
AudioActivity.ViewPagerAdapter adapter;
private void setupViewPager(ViewPager viewPager) {
adapter = new AudioActivity.ViewPagerAdapter(getSupportFragmentManager());
AudioPlayerAdapter audioPlayerAdapter=new AudioPlayerAdapter();
for(int i=0;i<audioList.size();i++) {
adapter.addFragment(audioPlayerAdapter.newInstance(audioList, i), AppConstants.AUDIO_PLAYER);
}
viewPager.setAdapter(adapter);
viewPager.setPageTransformer(true, new CubeInTransformer());
}
class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public void setFragment(Fragment fragment, int position,String title) {
mFragmentList.set(position,fragment);
mFragmentTitleList.set(position,title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
My Fragment
public class AudioPlayerAdapter extends Fragment implements SeekBar.OnSeekBarChangeListener {
Button btnStart, btnStop, btnBind, btnUnbind, btnUpby1, btnUpby10;
TextView textStatus, textIntValue, textStrValue;
Messenger mService = null;
boolean mIsBound;
public static Handler messageHandler;
long duration, currSongPosition;
ImageView displayArt;
TextView playerName;
TextView totTime;
TextView fromTime;
List<PlayerModel> songList;
RecyclerView songRecyclerView;
ImageButton showList;
ImageButton playAudio;
ImageButton pauseAudio;
ImageButton stepForward;
ImageButton stepBackward;
ImageButton shuffleAudio;
ImageButton volumeAudio;
ImageButton repeatAudio;
int songPosition;
SeekBar songProgressBar;
SeekBar volumeSeekBar;
private Intent playIntent;
//binding
private boolean musicBound = false;
private float x1, x2;
static final int MIN_DISTANCE = 150;
//activity and playback pause flags
private boolean paused = false, playbackPaused = false;
private Handler mHandler = new Handler();
private int seekForwardTime = 5000; // 5000 milliseconds
private int seekBackwardTime = 5000; // 5000 milliseconds
private int currentSongIndex = 0;
private boolean isShuffle = false;
private boolean isRepeat = false;
public AudioPlayerAdapter newInstance(List<PlayerModel> playerList, int position) {
AudioPlayerAdapter fragment = new AudioPlayerAdapter();
Bundle b = new Bundle();
b.putParcelableArrayList(AppConstants.SONG_LIST, (ArrayList<? extends Parcelable>) playerList);
b.putInt(AppConstants.SONG_POSITION, position);
fragment.setArguments(b);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.activity_music_player, container, false);
songList = getArguments().getParcelableArrayList(getString(R.string.SONG_LIST));
songPosition = getArguments().getInt(getString(R.string.SONG_POSITION), 0);
LogUtil.error("Song Position",songPosition+"-->"+songList.get(songPosition).getPlayerTitle());
FieldIntialization(view);
if (playIntent == null) {
playIntent = new Intent(getActivity(), MusicService.class);
playIntent.setAction(String.valueOf(MusicService.MSG_FOREGROUND));
playIntent.putParcelableArrayListExtra(getString(R.string.SONG_LIST), (ArrayList<? extends Parcelable>) songList);
playIntent.putExtra(getString(R.string.SONG_POSITION), songPosition);
getActivity().startService(playIntent);
}
DataInitialization(songPosition);
messageHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case MusicService.MSG_SET_INT_VALUE:
break;
case MusicService.MSG_PLAY:
LogUtil.error("Pause", "Pause");
playAudio.setImageResource(R.drawable.ic_pause_white_24dp);
break;
case MusicService.MSG_PAUSE:
LogUtil.error("Play", "Play");
playAudio.setImageResource(R.drawable.ic_play_white_24dp);
break;
case MusicService.MSG_NEXT:
songPosition = msg.getData().getInt(getString(R.string.SONG_POSITION));
LogUtil.error("SonPos", String.valueOf(songPosition));
updatePlayerView(songPosition);
break;
case MusicService.MSG_PREVIOUS:
songPosition = msg.getData().getInt(getString(R.string.SONG_POSITION));
LogUtil.error("SonPos", String.valueOf(songPosition));
updatePlayerView(songPosition);
break;
case MusicService.MSG_UPDATE_SEEKBAR:
duration = msg.getData().getLong(getString(R.string.SONG_DURATION));
currSongPosition = msg.getData().getLong(getString(R.string.SONG_CURR_DURATION));
break;
case MusicService.MSG_SHUFFLE_OFF:
Toast.makeText(getActivity(), "Shuffle Off", Toast.LENGTH_SHORT).show();
break;
case MusicService.MSG_SHUFFLE_ON:
Toast.makeText(getActivity(), "Shuffle On", Toast.LENGTH_SHORT).show();
break;
case MusicService.MSG_REPEAT_ON:
Toast.makeText(getActivity(), "Repeat On", Toast.LENGTH_SHORT).show();
break;
case MusicService.MSG_REPEAT_OFF:
Toast.makeText(getActivity(), "Repeat Off", Toast.LENGTH_SHORT).show();
break;
case MusicService.MSG_CLOSE:
getActivity().finish();
break;
case MusicService.MSG_STOP:
break;
default:
super.handleMessage(msg);
}
}
};
return view;
}
/* #Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
*//* outState.putString("textStatus", textStatus.getText().toString());
outState.putString("textIntValue", textIntValue.getText().toString());
outState.putString("textStrValue", textStrValue.getText().toString());*//*
}
private void restoreMe(Bundle state) {
if (state != null) {*//*
textStatus.setText(state.getString("textStatus"));
textIntValue.setText(state.getString("textIntValue"));
textStrValue.setText(state.getString("textStrValue"));*//*
}
}*/
public void stopService() {
getActivity().stopService(new Intent(getActivity(), MusicService.class));
}
private void sendMessageToService(int action) {
Intent startIntent = new Intent(getActivity(), MusicService.class);
startIntent.setAction(String.valueOf(action));
getActivity().startService(startIntent);
}
private void sendMessageToServiceWithData(int action, int currPosition) {
Intent startIntent = new Intent(getActivity(), MusicService.class);
startIntent.setAction(String.valueOf(action));
startIntent.putExtra(getString(R.string.SEEK_POSITION), currPosition);
getActivity().startService(startIntent);
}
private void FieldIntialization(View view) {
songProgressBar = (SeekBar) view.findViewById(R.id.seekBar);
volumeSeekBar = (SeekBar) view.findViewById(R.id.volumeSeekBar);
displayArt = (ImageView) view.findViewById(R.id.songImage);
playerName = (TextView) view.findViewById(R.id.songName);
totTime = (TextView) view.findViewById(R.id.endTime);
fromTime = (TextView) view.findViewById(R.id.startTime);
songRecyclerView = (RecyclerView) view.findViewById(R.id.songRecyclerView);
showList = (ImageButton) view.findViewById(R.id.showList);
stepForward = (ImageButton) view.findViewById(R.id.step_next);
stepBackward = (ImageButton) view.findViewById(R.id.step_prev);
shuffleAudio = (ImageButton) view.findViewById(R.id.shuffle);
repeatAudio = (ImageButton) view.findViewById(R.id.repeat);
playAudio = (ImageButton) view.findViewById(R.id.play_pause);
volumeAudio = (ImageButton) view.findViewById(R.id.speaker);
playAudio.setImageResource(R.drawable.ic_pause_white_24dp);
songRecyclerView.addItemDecoration(new MarginDecoration(getActivity()));
songRecyclerView.setHasFixedSize(true);
songRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),
LinearLayoutManager.HORIZONTAL, false));
SongRecyclerAdapter songRecyclerAdapter = new SongRecyclerAdapter(songList,
getActivity()
);
if (songList.size() > 0) {
LinearLayout.LayoutParams lp =
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
songRecyclerView.setLayoutParams(lp);
} else {
LinearLayout.LayoutParams lp =
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
songRecyclerView.setLayoutParams(lp);
}
songRecyclerView.setAdapter(songRecyclerAdapter);
songRecyclerAdapter.setOnDataChangeListener(new onRefreshFavListener() {
#Override
public void onFavRefresh(int position) {
playIntent = new Intent(getActivity(), MusicService.class);
playIntent.setAction(String.valueOf(MusicService.MSG_FOREGROUND));
playIntent.putParcelableArrayListExtra(getString(R.string.SONG_LIST), (ArrayList<? extends Parcelable>) songList);
playIntent.putExtra(getString(R.string.SONG_POSITION), position);
getActivity().startService(playIntent);
updatePlayerView(position);
}
});
}
private void DataInitialization(final int position) {
showList.setBackgroundResource(R.drawable.ic_up_white_24dp);
showList.setTag(R.drawable.ic_up_white_24dp);
songRecyclerView.setVisibility(View.GONE);
LogUtil.error("Update",position+"-->"+songList.get(position));
updatePlayerView(position);
showList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if ((int) showList.getTag() == R.drawable.ic_up_white_24dp) {
showList.setBackgroundResource(R.drawable.ic_down_white_24dp);
showList.setTag(R.drawable.ic_down_white_24dp);
songRecyclerView.setVisibility(View.VISIBLE);
} else {
showList.setBackgroundResource(R.drawable.ic_up_white_24dp);
showList.setTag(R.drawable.ic_up_white_24dp);
songRecyclerView.setVisibility(View.GONE);
}
}
});
songProgressBar.setOnSeekBarChangeListener(this);
final AudioManager audioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
volumeSeekBar.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumeSeekBar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
volumeSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
}
#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2) {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
progress, 0);
}
});
playAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
sendMessageToService(MusicService.MSG_CHECK_PLAYING_STATUS);
}
});
stepForward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessageToService(MusicService.MSG_NEXT);
}
});
stepBackward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessageToService(MusicService.MSG_PREVIOUS);
}
});
shuffleAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessageToService(MusicService.MSG_SHUFFLE);
}
});
repeatAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessageToService(MusicService.MSG_REPEAT);
}
});
}
public void updatePlayerView(int songIndex) {
playAudio.setImageResource(R.drawable.ic_pause_white_24dp);
LogUtil.error("Song List",songIndex+"-->"+songList.get(songIndex).getPlayerTitle());
playerName.setText(songList.get(songIndex).getPlayerTitle());
totTime.setText(Utility.convertDuration(Long.parseLong(songList.get(songIndex).getPlayerDuration())));
Cursor cursor = getActivity().getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM_ART},
MediaStore.Audio.Albums._ID + "=?",
new String[]{String.valueOf(songList.get(songIndex).getPlayerAlbumId())},
null);
cursor.moveToFirst();
displayArt.setScaleType(ImageView.ScaleType.FIT_XY);
displayArt.setImageBitmap(Constants.getDefaultAlbumArt(getActivity(), songList.get(songIndex).getPlayerAlbumId()));
songProgressBar.setProgress(0);
songProgressBar.setMax(100);
// Updating progress bar
updateProgressBar();
}
public void updateProgressBar() {
// mHandler.postDelayed(mUpdateTimeTask, 100);
}
/**
* Background Runnable thread
*/
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
sendMessageToService(MusicService.MSG_UPDATE_SEEKBAR);
// Displaying Total Duration time
totTime.setText("" + Utility.milliSecondsToTimer(duration));
// Displaying time completed playing
fromTime.setText("" + Utility.milliSecondsToTimer(currSongPosition));
// Updating progress bar
int progress = (int) (Utility.getProgressPercentage(currSongPosition, duration));
//Log.d("Progress", ""+progress);
songProgressBar.setProgress(progress);
// Running this thread after 100 milliseconds
mHandler.postDelayed(this, 100);
}
};
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
}
/**
* When user starts moving the progress handler
*/
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// remove message Handler from updating progress bar
// mHandler.removeCallbacks(mUpdateTimeTask);
}
/**
* When user stops moving the progress hanlder
*/
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// mHandler.removeCallbacks(mUpdateTimeTask);
int currentPosition = Utility.progressToTimer(seekBar.getProgress(), (int) duration);
sendMessageToServiceWithData(MusicService.MSG_SEEK, currentPosition);
// update timer progress again
updateProgressBar();
}
}
In my android application while I'm playing a music, the seekbar bar is staying still. The timer of the music is running fine & the music plays from the touched position of the seek bar.
But the problem is that the seekbar is still and not moving while touching on the seekbar .
Any one help me to find a solution for this .. Thank You ..
My Activity code is ....
public class Device_AudioPlayerActivity extends Activity implements Runnable,
OnClickListener, SeekBar.OnSeekBarChangeListener {
Button btnBack;
static Button btnPause;
private Handler mHandler;
Button btnNext;
static Button btnPlay;
static TextView textNowPlaying;
static TextView textAlbumArtist;
static TextView textComposer;
static LinearLayout linearLayoutPlayer;
SeekBar progressBar;
static Context context;
TextView textBufferDuration, textDuration;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//getActionBar().hide();
setContentView(R.layout.device_audio_player);
context = this;
progressBar=(SeekBar)findViewById(R.id.progressBar);
init();
progressBar.setMax(Device_SongService.mp.getDuration());
new Thread().start();
progressBar.setOnSeekBarChangeListener(this);
progressBar.setEnabled(true);
//-=--------------------------------------
}
private void init() {
getViews();
setListeners();
progressBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.white), Mode.SRC_IN);
Device_PlayerConstants.PROGRESSBAR_HANDLER = new Handler() {
#Override
public void handleMessage(Message msg) {
Integer i[] = (Integer[]) msg.obj;
textBufferDuration.setText(Device_UtilFunctions.getDuration(i[0]));
textDuration.setText(Device_UtilFunctions.getDuration(i[1]));
progressBar.setProgress(i[2]);
}
};
}
private void setListeners() {
btnBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Device_Controls.previousControl(getApplicationContext());
}
});
btnPause.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Device_Controls.pauseControl(getApplicationContext());
}
});
btnPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Device_Controls.playControl(getApplicationContext());
}
});
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Device_Controls.nextControl(getApplicationContext());
}
});
}
public static void changeUI() {
updateUI();
changeButton();
}
private void getViews() {
btnBack = (Button) findViewById(R.id.btnBack);
btnPause = (Button) findViewById(R.id.btnPause);
btnNext = (Button) findViewById(R.id.btnNext);
btnPlay = (Button) findViewById(R.id.btnPlay);
textNowPlaying = (TextView) findViewById(R.id.textNowPlaying);
linearLayoutPlayer = (LinearLayout) findViewById(R.id.linearLayoutPlayer);
textAlbumArtist = (TextView) findViewById(R.id.textAlbumArtist);
textComposer = (TextView) findViewById(R.id.textComposer);
progressBar = (SeekBar) findViewById(R.id.progressBar);
textBufferDuration = (TextView) findViewById(R.id.textBufferDuration);
textDuration = (TextView) findViewById(R.id.textDuration);
textNowPlaying.setSelected(true);
textAlbumArtist.setSelected(true);
}
#Override
protected void onResume() {
super.onResume();
boolean isServiceRunning = Device_UtilFunctions.isServiceRunning(Device_SongService.class.getName(), getApplicationContext());
if (isServiceRunning) {
updateUI();
}
changeButton();
}
public static void changeButton() {
if (Device_PlayerConstants.SONG_PAUSED) {
btnPause.setVisibility(View.GONE);
btnPlay.setVisibility(View.VISIBLE);
} else {
btnPause.setVisibility(View.VISIBLE);
btnPlay.setVisibility(View.GONE);
}
}
private static void updateUI() {
try {
String songName = Device_PlayerConstants.SONGS_LIST.get(Device_PlayerConstants.SONG_NUMBER).getTitle();
String artist = Device_PlayerConstants.SONGS_LIST.get(Device_PlayerConstants.SONG_NUMBER).getArtist();
String album = Device_PlayerConstants.SONGS_LIST.get(Device_PlayerConstants.SONG_NUMBER).getAlbum();
String composer = Device_PlayerConstants.SONGS_LIST.get(Device_PlayerConstants.SONG_NUMBER).getComposer();
textNowPlaying.setText(songName);
textAlbumArtist.setText(artist + " - " + album);
if (composer != null && composer.length() > 0) {
textComposer.setVisibility(View.VISIBLE);
textComposer.setText(composer);
} else {
textComposer.setVisibility(View.GONE);
}
} catch (Exception e) {
e.printStackTrace();
}
try {
long albumId = Device_PlayerConstants.SONGS_LIST.get(Device_PlayerConstants.SONG_NUMBER).getAlbumId();
Bitmap albumArt = Device_UtilFunctions.getAlbumart(context, albumId);
if (albumArt != null) {
linearLayoutPlayer.setBackgroundDrawable(new BitmapDrawable(albumArt));
} else {
linearLayoutPlayer.setBackgroundDrawable(new BitmapDrawable(Device_UtilFunctions.getDefaultAlbumArt(context)));
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onClick(View view) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
try {
if (Device_SongService.mp.isPlaying() || Device_SongService.mp != null) {
if (b)
Device_SongService.mp.seekTo(i);
} else if (Device_SongService.mp == null) {
Toast.makeText(getApplicationContext(), "Media is not running",
Toast.LENGTH_SHORT).show();
seekBar.setProgress(0);
}
} catch (Exception e) {
Log.e("seek bar", "" + e);
seekBar.setEnabled(false);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void run() {
int currentPosition = Device_SongService.mp.getCurrentPosition();
int total = Device_SongService.mp.getDuration();
while (Device_SongService.mp != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = Device_SongService.mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
progressBar.setProgress(currentPosition);
}
}
}
Have a look at this link.
Try using a thread in progress changed.
you have to use thread on onprogresschnaged....
#Override
public void onProgressChanged(SeekBar arg0, final int progress, boolean arg2) {
Thread thread = new Thread() {
#Override
public void run() {
try {
while(true) {
//here write your code
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
}
I have the problem with the seekbar thumb, although I have added every necessary codes for it to work. still the seekbar thumb doesn't play from the point dragged by the user. instead the thumb positioned itself back to the point it was last playing though. Any help will be appreciated.
plus = (ImageButton) findViewById(R.id.imageButton2);
minus = (ImageButton) findViewById(R.id.imageButton4);
player = MediaPlayer.create(this, R.raw.songnames);
player.setLooping(false);
im = (ImageButton) this.findViewById(R.id.imageButton3);
seekbar = (SeekBar) findViewById(R.id.mantraProgressBar);
seekbar.setVisibility(ProgressBar.VISIBLE);
seekbar.setProgress(0);
seekbar.setMax(player.getDuration());
new Thread(this).start();
im.setOnClickListener(this);
player.start();
im.setImageResource(R.drawable.pause_tran);
Toast.makeText(this, isPlaying, Toast.LENGTH_LONG).show();
plus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int cu = player.getCurrentPosition();
player.seekTo(cu - 5000);
}
});
minus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int cu = player.getCurrentPosition();
player.seekTo(cu + 5000);
}
});
}
#Override
public void onClick(View arg0) {
if (arg0.getId() == R.id.imageButton3) {
if (player.isPlaying()) {
player.pause();
Toast.makeText(this, notPlaying, Toast.LENGTH_LONG).show();
ImageButton img1 = (ImageButton) this.findViewById(R.id.imageButton3);
img1.setImageResource(R.drawable.play_tran);
} else {
player.start();
Toast.makeText(this, isPlaying, Toast.LENGTH_LONG).show();
ImageButton img1 = (ImageButton) this.findViewById(R.id.imageButton3);
img1.setImageResource(R.drawable.pause_tran);
}
}
}
#Override
public void run() {
int currentPosition = 0;
String s;
int total = player.getDuration();
while (player != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = player.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekbar.setProgress(currentPosition);
}
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
player.seekTo(progress);
seekbar.setProgress(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
public class MainActivity extends AppCompatActivity {
private MyVideoView mVV;
private Handler mhandler;
private SeekBar seekbar;
private int duration;
private int backPositon = 0;
private int currentPosition;
private SharedPreferences sp;
private MediaController controller;
private TextView tv_curr;
private TextView tv_duration;
private Handler handler;
private boolean mExit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mVV = (MyVideoView) findViewById(R.id.vv);
seekbar = (SeekBar) findViewById(R.id.seekbar);
tv_curr = (TextView) findViewById(R.id.tv_currtime);
tv_duration = (TextView) findViewById(R.id.tv_duration);
//get duration of video
getDuration();
//video start
playVideo();
//get current time
getCurrentDuration();
//listener
initEvent();
}
private void initHanlder() {
handler=new Handler(){
#Override
public void handleMessage(Message msg) {
if (msg.what==0x123){
tv_curr.setText(timeFormat(mVV.getCurrentPosition()));
seekbar.setProgress(mVV.getCurrentPosition());
}
if(msg.what==0x133){
int changedProgress = msg.arg1;
tv_curr.setText(timeFormat(changedProgress));
mVV.seekTo(changedProgress);
seekbar.setProgress(changedProgress);
mVV.start();
}
}
};
new Thread(new Runnable() {
#Override
public void run() {
while (mVV.getCurrentPosition()<duration){
Message message = Message.obtain();
message.what=0x123;
handler.sendMessage(message);
SystemClock.sleep(1000);
if(mExit){
break;
}
}
}
}).start();
}
private void getDuration() {
mVV.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
duration = mVV.getDuration();
timeFormat(duration);
Log.d("TAG", "---duration" + timeFormat(duration));
seekbar.setMax(duration);
//TextView time
tv_duration.setText(timeFormat(duration));
//init handler
initHanlder();
}
});
}
private String timeFormat(int time) {
StringBuilder mFormatBuilder;
Formatter mFormatter;
mFormatBuilder = new StringBuilder();
mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
int totalSeconds = time / 1000;
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
mFormatBuilder.setLength(0);
if (hours > 0) {
return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
} else {
return mFormatter.format("%02d:%02d", minutes, seconds).toString();
}
}
private void playVideo() {
File file = new File(Environment.getExternalStorageDirectory(), "cgx_video/db.mp4");
if (!file.exists()) {
file.mkdir();
}
Log.d("TAG", file.toString());
mVV.setVideoPath(file.getPath());
mVV.start();
}
private void initEvent() {
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
currentPosition=progress;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
mVV.pause();
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
if(handler!=null){
Message message = Message.obtain();
message.what=0x133;
message.arg1=currentPosition;
handler.sendMessage(message);
}
}
});
}
#Override
protected void onPause() {
super.onPause();
Log.d("TAG", "---onPause");
mVV.pause();
backPositon = mVV.getCurrentPosition();
Log.d("TAG", "backPositon:" + backPositon);
}
#Override
protected void onStop() {
super.onStop();
Log.d("TAG", "---onStop");
}
#Override
protected void onResume() {
super.onResume();
Log.d("TAG", backPositon + "---backPositon");
mVV.seekTo(backPositon);
mVV.start();
}
#Override
protected void onDestroy() {
//in case of leak of memeroy
mExit=true;
super.onDestroy();
}
}
I've (legally) copied and pasted some project code from an app called beatkeeper into my own app. I wanted to implement a metronome.
The app beatkeeper on itself works fine but as I soon as I copy the code and run my own app, it's stops working the moment I click the start/stop button...
04-07 09:25:05.126: E/AndroidRuntime(2708): FATAL EXCEPTION: main
04-07 09:25:05.126: E/AndroidRuntime(2708): Process: nl.ruudjanssenmusicservices.desaxofoonapp, PID: 2708
04-07 09:25:05.126: E/AndroidRuntime(2708): java.lang.NullPointerException
04-07 09:25:05.126: E/AndroidRuntime(2708): at nl.ruudjanssenmusicservices.desaxofoonapp.MetronomeActivity$6.handleMessage(MetronomeActivity.java:54)
04-07 09:25:05.126: E/AndroidRuntime(2708): at android.os.Handler.dispatchMessage(Handler.java:102)
04-07 09:25:05.126: E/AndroidRuntime(2708): at android.os.Looper.loop(Looper.java:136)
04-07 09:25:05.126: E/AndroidRuntime(2708): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-07 09:25:05.126: E/AndroidRuntime(2708): at java.lang.reflect.Method.invokeNative(Native Method)
04-07 09:25:05.126: E/AndroidRuntime(2708): at java.lang.reflect.Method.invoke(Method.java:515)
04-07 09:25:05.126: E/AndroidRuntime(2708): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-07 09:25:05.126: E/AndroidRuntime(2708): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-07 09:25:05.126: E/AndroidRuntime(2708): at dalvik.system.NativeStart.main(Native Method)
Source main activity:
package nl.ruudjanssenmusicservices.desaxofoonapp;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
public class MetronomeActivity extends Activity {
private final short minBpm = 40;
private final short maxBpm = 208;
private short bpm = 100;
private short noteValue = 4;
private short beats = 4;
private short volume;
private short initialVolume;
private double beatSound = 2440;
private double sound = 6440;
private AudioManager audio;
private MetronomeAsyncTask metroTask;
private Button plusButton;
private Button minusButton;
private TextView currentBeat;
private Handler mHandler;
// have in mind that: http://stackoverflow.com/questions/11407943/this-handler-class-should-be-static-or-leaks-might-occur-incominghandler
// in this case we should be fine as no delayed messages are queued
private Handler getHandler() {
return new Handler() {
#Override
public void handleMessage(Message msg) {
String message = (String)msg.obj;
if(message.equals("1"))
currentBeat.setTextColor(Color.GREEN);
else
currentBeat.setTextColor(getResources().getColor(R.color.yellow));
currentBeat.setText(message);
}
};
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
metroTask = new MetronomeAsyncTask();
/* Set values and listeners to buttons and stuff */
TextView bpmText = (TextView) findViewById(R.id.bps);
bpmText.setText(""+bpm);
TextView timeSignatureText = (TextView) findViewById(R.id.timesignature);
timeSignatureText.setText(""+beats+"/"+noteValue);
plusButton = (Button) findViewById(R.id.plus);
plusButton.setOnLongClickListener(plusListener);
minusButton = (Button) findViewById(R.id.minus);
minusButton.setOnLongClickListener(minusListener);
// currentBeat = (TextView) findViewById(R.id.currentBeat);
//currentBeat.setTextColor(Color.GREEN);
Spinner beatSpinner = (Spinner) findViewById(R.id.beatspinner);
ArrayAdapter<Beats> arrayBeats =
new ArrayAdapter<Beats>(this,
android.R.layout.simple_spinner_item, Beats.values());
beatSpinner.setAdapter(arrayBeats);
beatSpinner.setSelection(Beats.four.ordinal());
arrayBeats.setDropDownViewResource(R.layout.spinner_dropdown);
beatSpinner.setOnItemSelectedListener(beatsSpinnerListener);
Spinner noteValuesdSpinner = (Spinner) findViewById(R.id.notespinner);
ArrayAdapter<NoteValues> noteValues =
new ArrayAdapter<NoteValues>(this,
android.R.layout.simple_spinner_item, NoteValues.values());
noteValuesdSpinner.setAdapter(noteValues);
noteValues.setDropDownViewResource(R.layout.spinner_dropdown);
noteValuesdSpinner.setOnItemSelectedListener(noteValueSpinnerListener);
audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
initialVolume = (short) audio.getStreamVolume(AudioManager.STREAM_MUSIC);
volume = initialVolume;
SeekBar volumebar = (SeekBar) findViewById(R.id.volumebar);
volumebar.setMax(audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumebar.setProgress(volume);
volumebar.setOnSeekBarChangeListener(volumeListener);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public synchronized void onStartStopClick(View view) {
Button button = (Button) view;
String buttonText = button.getText().toString();
if(buttonText.equalsIgnoreCase("start")) {
button.setText(R.string.stop);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
metroTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
else
metroTask.execute();
} else {
button.setText(R.string.start);
metroTask.stop();
metroTask = new MetronomeAsyncTask();
Runtime.getRuntime().gc();
}
}
private void maxBpmGuard() {
if(bpm >= maxBpm) {
plusButton.setEnabled(false);
plusButton.setPressed(false);
} else if(!minusButton.isEnabled() && bpm>minBpm) {
minusButton.setEnabled(true);
}
}
public void onPlusClick(View view) {
bpm++;
TextView bpmText = (TextView) findViewById(R.id.bps);
bpmText.setText(""+bpm);
metroTask.setBpm(bpm);
maxBpmGuard();
}
private OnLongClickListener plusListener = new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
bpm+=20;
if(bpm >= maxBpm)
bpm = maxBpm;
TextView bpmText = (TextView) findViewById(R.id.bps);
bpmText.setText(""+bpm);
metroTask.setBpm(bpm);
maxBpmGuard();
return true;
}
};
private void minBpmGuard() {
if(bpm <= minBpm) {
minusButton.setEnabled(false);
minusButton.setPressed(false);
} else if(!plusButton.isEnabled() && bpm<maxBpm) {
plusButton.setEnabled(true);
}
}
public void onMinusClick(View view) {
bpm--;
TextView bpmText = (TextView) findViewById(R.id.bps);
bpmText.setText(""+bpm);
metroTask.setBpm(bpm);
minBpmGuard();
}
private OnLongClickListener minusListener = new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
bpm-=20;
if(bpm <= minBpm)
bpm = minBpm;
TextView bpmText = (TextView) findViewById(R.id.bps);
bpmText.setText(""+bpm);
metroTask.setBpm(bpm);
minBpmGuard();
return true;
}
};
private OnSeekBarChangeListener volumeListener = new OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
volume = (short) progress;
audio.setStreamVolume(AudioManager.STREAM_MUSIC, progress, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
};
private OnItemSelectedListener beatsSpinnerListener = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Beats beat = (Beats) arg0.getItemAtPosition(arg2);
TextView timeSignature = (TextView) findViewById(R.id.timesignature);
timeSignature.setText(""+beat+"/"+noteValue);
metroTask.setBeat(beat.getNum());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
private OnItemSelectedListener noteValueSpinnerListener = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
NoteValues noteValue = (NoteValues) arg0.getItemAtPosition(arg2);
TextView timeSignature = (TextView) findViewById(R.id.timesignature);
timeSignature.setText(""+beats+"/"+noteValue);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
#Override
public boolean onKeyUp(int keycode, KeyEvent e) {
SeekBar volumebar = (SeekBar) findViewById(R.id.volumebar);
volume = (short) audio.getStreamVolume(AudioManager.STREAM_MUSIC);
switch(keycode) {
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_DOWN:
volumebar.setProgress(volume);
break;
}
return super.onKeyUp(keycode, e);
}
public void onBackPressed() {
metroTask.stop();
// metroTask = new MetronomeAsyncTask();
Runtime.getRuntime().gc();
audio.setStreamVolume(AudioManager.STREAM_MUSIC, initialVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
finish();
}
private class MetronomeAsyncTask extends AsyncTask<Void,Void,String> {
Metronome metronome;
MetronomeAsyncTask() {
mHandler = getHandler();
metronome = new Metronome(mHandler);
}
protected String doInBackground(Void... params) {
metronome.setBeat(beats);
metronome.setNoteValue(noteValue);
metronome.setBpm(bpm);
metronome.setBeatSound(beatSound);
metronome.setSound(sound);
metronome.play();
return null;
}
public void stop() {
metronome.stop();
metronome = null;
}
public void setBpm(short bpm) {
metronome.setBpm(bpm);
metronome.calcSilence();
}
public void setBeat(short beat) {
if(metronome != null)
metronome.setBeat(beat);
}
}
}
I think there might be a problem with the 'private Handler getHandler' on line 48, but I have absolutely no clue how to solve this...
Edit: request to post the metronome-class:
package nl.ruudjanssenmusicservices.desaxofoonapp;
import android.os.Handler;
import android.os.Message;
public class Metronome {
private double bpm;
private int beat;
private int noteValue;
private int silence;
private double beatSound;
private double sound;
private final int tick = 1000; // samples of tick
private boolean play = true;
private AudioGenerator audioGenerator = new AudioGenerator(8000);
private Handler mHandler;
private double[] soundTickArray;
private double[] soundTockArray;
private double[] silenceSoundArray;
private Message msg;
private int currentBeat = 1;
public Metronome(Handler handler) {
audioGenerator.createPlayer();
this.mHandler = handler;
}
public void calcSilence() {
silence = (int) (((60/bpm)*8000)-tick);
soundTickArray = new double[this.tick];
soundTockArray = new double[this.tick];
silenceSoundArray = new double[this.silence];
msg = new Message();
msg.obj = ""+currentBeat;
double[] tick = audioGenerator.getSineWave(this.tick, 8000, beatSound);
double[] tock = audioGenerator.getSineWave(this.tick, 8000, sound);
for(int i=0;i<this.tick;i++) {
soundTickArray[i] = tick[i];
soundTockArray[i] = tock[i];
}
for(int i=0;i<silence;i++)
silenceSoundArray[i] = 0;
}
public void play() {
calcSilence();
do {
msg = new Message();
msg.obj = ""+currentBeat;
if(currentBeat == 1)
audioGenerator.writeSound(soundTockArray);
// else
// audioGenerator.writeSound(soundTickArray);
if(bpm <= 120)
mHandler.sendMessage(msg);
audioGenerator.writeSound(silenceSoundArray);
if(bpm > 120)
mHandler.sendMessage(msg);
currentBeat++;
if(currentBeat > beat)
currentBeat = 1;
} while(play);
}
public void stop() {
play = false;
audioGenerator.destroyAudioTrack();
}
public double getBpm() {
return bpm;
}
public void setBpm(int bpm) {
this.bpm = bpm;
}
public int getNoteValue() {
return noteValue;
}
public void setNoteValue(int bpmetre) {
this.noteValue = bpmetre;
}
public int getBeat() {
return beat;
}
public void setBeat(int beat) {
this.beat = beat;
}
public double getBeatSound() {
return beatSound;
}
public void setBeatSound(double sound1) {
this.beatSound = sound1;
}
public double getSound() {
return sound;
}
public void setSound(double sound2) {
this.sound = sound2;
}
}
currentBeat is null there in onHandleMessage();