Search code examples
scalaaudiobeep

Scala - Playing a Sound -Beeping


I am tryig to do something in order that to have a beep or sound for 2-3 minutes when a proces is done in my app. Currently I have this:

object SoundPlay {
import scala.collection.mutable.ListBuffer
val bb = new ListBuffer[Any]

def main(args: Array[String]) {

   val beep = java.awt.Toolkit.getDefaultToolkit.beep
   for (i <- 1 to 100) {
     bb += beep
   }

   bb.foreach(println(_))

  }
}

but this one makes only one sound and I can't make it repeated moe than Once.?!

My UPDATE

I wrote this and is a kind of:

object SoundPlay {
def main(args: Array[String]) {
   for(i <- 1 to 10) {
     Thread.sleep(1000)
     java.awt.Toolkit.getDefaultToolkit.beep()
    }
  }
 }

Solution

  • beep is a nasty side-effecting method. If you want to repeat it you'll have to capture it via something like scalaz Task:

    import scalaz._, Scalaz._, concurrent.Task
    
    val beepTask = Task(java.awt.Toolkit.getDefaultToolkit.beep)
    //traverse so we gather the 100 Tasks into a single Task
    val bb = (1 to 100).toList traverse {_ => beepTask}
    //everything is "lazy" until we call run, that's when the beeps actually happen
    bb.run