mirror of
https://github.com/NohamR/Pocket-Bird.git
synced 2026-05-25 04:07:23 +00:00
Add chirping when pet
This commit is contained in:
@@ -2,6 +2,7 @@ import Frame from './frame.js';
|
||||
import Layer from './layer.js';
|
||||
import Anim from './anim.js';
|
||||
import { Birb, Animations } from './birb.js';
|
||||
import { Birdsong } from './sound.js';
|
||||
import { Context, ObsidianContext } from './context.js';
|
||||
|
||||
import {
|
||||
@@ -203,6 +204,8 @@ function startApplication(birbPixels, featherPixels) {
|
||||
FLYING: "flying",
|
||||
};
|
||||
|
||||
const birdsong = new Birdsong();
|
||||
|
||||
let frozen = false;
|
||||
let stateStart = Date.now();
|
||||
let currentState = States.IDLE;
|
||||
@@ -897,6 +900,7 @@ function startApplication(birbPixels, featherPixels) {
|
||||
|
||||
function pet() {
|
||||
if (currentState === States.IDLE && birb.getCurrentAnimation() !== Animations.HEART) {
|
||||
birdsong.chirp();
|
||||
birb.setAnimation(Animations.HEART);
|
||||
lastPetTimestamp = Date.now();
|
||||
}
|
||||
|
||||
42
src/sound.js
Normal file
42
src/sound.js
Normal file
@@ -0,0 +1,42 @@
|
||||
// @ts-check
|
||||
|
||||
export class Birdsong {
|
||||
|
||||
/**
|
||||
* @type {AudioContext}
|
||||
*/
|
||||
audioContext;
|
||||
|
||||
chirp() {
|
||||
if (!this.audioContext) {
|
||||
this.audioContext = new AudioContext();
|
||||
}
|
||||
|
||||
const TIMES = [0, 0.06, 0.16];
|
||||
const FREQUENCIES = [2200,
|
||||
3500 + Math.random() * 700,
|
||||
1600 + Math.random() * 400];
|
||||
const VOLUMES = [0.0001, 0.3, 0.0001];
|
||||
|
||||
const oscillator = this.audioContext.createOscillator();
|
||||
oscillator.type = "sine";
|
||||
const gain = this.audioContext.createGain();
|
||||
oscillator.connect(gain);
|
||||
gain.connect(this.audioContext.destination);
|
||||
|
||||
const now = this.audioContext.currentTime;
|
||||
for (let i = 0; i < TIMES.length; i++) {
|
||||
const time = TIMES[i] + now;
|
||||
if (i === 0) {
|
||||
oscillator.frequency.setValueAtTime(FREQUENCIES[i], time);
|
||||
gain.gain.setValueAtTime(VOLUMES[i], time);
|
||||
} else {
|
||||
oscillator.frequency.exponentialRampToValueAtTime(FREQUENCIES[i], time);
|
||||
gain.gain.exponentialRampToValueAtTime(VOLUMES[i], time);
|
||||
}
|
||||
}
|
||||
|
||||
oscillator.start(now);
|
||||
oscillator.stop(now + TIMES[TIMES.length - 1]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user