How to Make a Countdown Timer Like in a Music Player

How can I make a countdown timer like in a music player?

You should take a look at NSDate property timeIntervalSinceNow. All you need is to set a future date as the endDate using NSDate method dateByAddingTimeInterval as follow:

class ViewController: UIViewController {

@IBOutlet weak var timerLabel: UILabel!

var remainingTime: NSTimeInterval = 0
var endDate: NSDate!
var timer = NSTimer()

override func viewDidLoad() {
super.viewDidLoad()
remainingTime = 228.0 // choose as many seconds as you want (total time)
endDate = NSDate().dateByAddingTimeInterval(remainingTime) // set your future end date by adding the time for your timer

timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "updateLabel", userInfo: nil, repeats: true) // create a timer to update your label
}
func updateLabel() {
timerLabel.text = endDate.timeIntervalSinceNow.mmss
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

// you will need this extension to convert your time interval to a time string

extension NSTimeInterval {
var mmss: String {
return self < 0 ? "00:00" : String(format:"%02d:%02d", Int((self/60.0)%60), Int(self % 60))
}
var hmmss: String {
return String(format:"%d:%02d:%02d", Int(self/3600.0), Int(self / 60.0 % 60), Int(self % 60))
}
}

Android app to play mp3 file in specific time with countdown timer

First, I'd recommend you only start your CountdownTimer in onStopTrackingTouch - reason being that currently you're creating a brand new timer every time the progress changes on your seekbar (which could be happening a lot).

Secondly, you'll need to retain a reference to your timer in order to cancel it. So:

public class MainActivity extends AppCompatActivity {

private CountdownTimer timer = null;

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

final SeekBar sb = (SeekBar) findViewById(R.id.seekBar);
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
restartTimer(seekBar);
}
}

final Button bt_stop = (Button) findViewById(R.id.btn1);
bt_stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(timer != null) {
timer.cancel();
}
}
});

}

private void restartTimer(SeekBar sb) {
if(timer!=null) {
timer.cancel();
}
final long millis = TimeUnit.SECONDS.toMillis(sb.getProgress());
final long interval = TimeUnit.SECONDS.toMillis(1);
timer = new CountdownTimer(millis, interval) {
@Override
public void onTick(long millisUntilFinished) {
tv.setText(String.format("Seconds Remaining: %d", TimeUnit.MILLIS.toSeconds(millisUntilFinished));
}

@Override
public void onFinish() {
tv.setText("done!");
}
}
timer.start();
}

}

How to autoplay audio when the countdown timer is finished?

By making you click this "START" button, they ask for an user gesture and thus have marked their document as approved-by-user to play audio. This means they are not subject for chrome's autoplay policies anymore.

Now, Safari by default is even stricter than Chrome here, and a simple click on the document doesn't work: in this browser you need to start the playback from the user-event itself.

So in your case, it won't work, even if you did start the countdown from a click like Google.

The solution is then to start the playback from the click event, and to pause it immediately after. Doing so, your Element will be marked as approved-by-user and you will ave full control over it.

const audio = new Audio("https://dl.dropboxusercontent.com/s/1cdwpm3gca9mlo0/kick.mp3");let time = 5;
btn.onclick = e => { // mark our audio element as approved by the user audio.play().then(() => { // pause directly audio.pause(); audio.currentTime = 0; }); countdown(); btn.disabled = true;};

function countdown() { pre.textContent = --time; if(time === 0) return onend(); setTimeout(countdown, 1000);}

function onend() { audio.play(); // now we're safe to play it time = 5; btn.disabled = false;}
<button id="btn">start countdown</button><br><pre id="pre"></pre>

Android Media Player Stuttering with CountDownTimer

There are lots of reports of Android MediaPlayer stutter with various ways to try to fix it. This seems to be the best related question:

  • MediaPlayer stutters at start of mp3 playback

However, AudioTrack might be better for your particular situation where you just want to play specific notes. See:

  • Playing an arbitrary tone with Android


Related Topics



Leave a reply



Submit