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
How to Chain Filters in Metal for iOS
Xcode 4.2 with Arc: Will My Code Run Even on iOS Devices with Firmware Older Than 5.0
Uialertview's Textfield Does Not Show Keyboard in iOS8
Case Insensitive Matching Search in String Array Swift 3
No Such Module Iqkeyboardmanagerswift
Change Cell Height by The Content of The Textview Inside The Cell
iOS Where to Put Custom Cell Design? Awakefromnib or Cellforrowatindexpath
Map Object into 2D Array Swift for Tableview Sections
Can't Build an App for Distribution After Joining Existing Enterprise Developer Program
iOS How to Get a List of Already Purchased Products
How to Add Frameworks into the Swift Project
Swift 4.2 Make Bottom of Tableview Move Up When Keyboard Shows
Custom Uibarbuttonitem with Bg Colour and Text Swift 3
Uibarbuttonitem Changing Title Not Working
Reusing View in UIpickerview with iOS 7
How to Get Index of Xcuielement in Xcuielementquery
How to Go to Specific Native View Controller from React-Native Code
Media_Err_Decode on HTML5 Video in iOS UIwebview After Many Plays