xx3. おまけ

■音を出す準備

import javax.sound.sampled._

import scala.util.Random

val line = AudioSystem.getSourceDataLine(new AudioFormat(44100, 8, 1, true, true))

line.open()

line.start()

def play(a:Array[Byte]) = line.write(a,0,a.length)

■8bitサウンドデータ化

Int 値を Byteの範囲(-128 - + 127)

+128 → -128 に

def lim0(x:Int):Byte = x.toByte

127 > → 127 、 -128 < → -128

def lim1(x:Int):Byte = if(x > 127) 127 else if(x < -128) -128 else x.toByte

■音源データ

// ノコギリ波を高さと長さを変えて繰り返し再生。だんだん 高く 短く

for(k <- 1 to 5; j <- 1 to 10) line.write(Array.tabulate(44100)(i => lim0(i*j)) , 0 , 44100/10/k)

// ブザー音

line.write(Array.tabulate(44100)(i => lim0(i*1)) , 0 , 44100)

// サイン派

line.write(Array.tabulate(44100)(i => (128*Math.sin(2*Math.PI *i/44100/1000)).toByte), 0, 44100)

(以下破棄)

// x からスタートし、+1づつ増加するストリーム

def seq3(x:Int):Stream[Int] = x #:: seq3(x + 1)

seq3(0) take 10 foreach println

Int 値を Byteの範囲(-128 - + 127)

+128 → -128 に

def lim0(x:Int):Byte = x.toByte

127 > → 127 、 -128 < → -128

def lim1(x:Int):Byte = if(x > 127) 127 else if(x < -128) -128 else x.toByte

3秒間分のバイトデータ化

def toBuf0(s:Stream[Int]) = s map(lim0 _) take 44100*3 toArray

3秒間分のバイトデータ化

def toBuf1(s:Stream[Int]) = s map(lim1 _) take 44100*3 toArray

正弦波 0 127 0 -128 0

def seq4(x:Int):Stream[Int] = (128*Math.sin(2*Math.PI*x/128.0 )).toInt #:: seq4(x + 1)

利用例

play (toBuf0( seq3(0) ))

play (toBuf1( seq4(0) ))