Skip to content

Commit

Permalink
Most functions are now complete in the simulator, but the background …
Browse files Browse the repository at this point in the history
…task seems to just end
  • Loading branch information
JohnVidler committed May 25, 2022
1 parent 6c4eece commit f711f6a
Show file tree
Hide file tree
Showing 3 changed files with 204 additions and 28 deletions.
21 changes: 21 additions & 0 deletions codal-audio-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
The MIT License (MIT)
Copyright (c) 2022 Lancaster University
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
22 changes: 22 additions & 0 deletions codal-audio.cpp
Original file line number Diff line number Diff line change
@@ -1,3 +1,25 @@
/*
The MIT License (MIT)
Copyright (c) 2022 Lancaster University
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/

#include "pxt.h"
#include "MicroBit.h"
#include "StreamRecording.h"
Expand Down
189 changes: 161 additions & 28 deletions codal-audio.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,25 @@
/*
The MIT License (MIT)
Copyright (c) 2022 Lancaster University
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/

enum AudioEvent {
//% block="Starts Playing"
StartedPlaying,
Expand All @@ -21,24 +43,113 @@ enum AudioGainEnum {
High
}

enum AudioRecordingMode {
Stopped,
Recording,
Playing
}

/**
* Functions to operate the v2 on-board microphone and speaker.
*/
//% weight=5 color=#e26fb4 icon="\uf130" block="V2 Audio" advanced=false
namespace codalAudio {

// Expressed in samples, as we can have varying recording and playback rates!
const MAX_SAMPLES: number = 55000
const INTERVAL_STEP: number = 100

// Shim state
let _moduleMode: AudioRecordingMode = AudioRecordingMode.Stopped;
let _recordingFreqHz: number = 22000
let _playbackFreqHz: number = 22000
let _micGain: AudioGainEnum = AudioGainEnum.Medium

/*let _memoryFill: number = 0
// Track if we have a simulator tick timer to use...
let _internalTimer: number = 0
let _memoryFill: number = 0
let _handlers: (() => void)[] = []

setInterval( () => {
if( _memoryFill < 100 )
_memoryFill++
console.log( _memoryFill )
}, 100 )*/
function __init__(): void {
if( _internalTimer !== 0 )
return
_internalTimer = 1

control.runInParallel( () => {
while (true) {

switch (_moduleMode) {
case AudioRecordingMode.Playing:
if (_memoryFill <= 0) {
_memoryFill = 0;
return __setMode__(AudioRecordingMode.Stopped)
}
_memoryFill -= _playbackFreqHz / (1000 / INTERVAL_STEP)
console.log(`PLAY --> Memory fill: ${_memoryFill}/${MAX_SAMPLES}, mode = ${_moduleMode}`)
break

case AudioRecordingMode.Recording:
if (_memoryFill >= MAX_SAMPLES) {
_memoryFill = MAX_SAMPLES;
return __setMode__(AudioRecordingMode.Stopped)
}
_memoryFill += _recordingFreqHz / (1000 / INTERVAL_STEP)
console.log(`RECD --> Memory fill: ${_memoryFill}/${MAX_SAMPLES}, mode = ${_moduleMode}`)
break
}

basic.pause( INTERVAL_STEP )
}
console.log( "Impossible code state! Emergency reset!" )
_internalTimer = 0
})
}

function __emitEvent__( type: AudioEvent ): void {
if( _handlers[type] !== undefined )
return _handlers[type]();
}

function __setMode__( mode: AudioRecordingMode ): void {
switch( mode ) {
case AudioRecordingMode.Stopped:
if( _moduleMode == AudioRecordingMode.Recording ) {
console.log( "Recording --> Stopped" )
_moduleMode = AudioRecordingMode.Stopped
return __emitEvent__( AudioEvent.StoppedRecording )
}

if( _moduleMode == AudioRecordingMode.Playing ) {
console.log("Playing --> Stopped")
_moduleMode = AudioRecordingMode.Stopped
return __emitEvent__( AudioEvent.StoppedPlaying )
}

console.log("Stopped --> Stopped")
_moduleMode = AudioRecordingMode.Stopped;
return

case AudioRecordingMode.Playing:
if( _moduleMode !== AudioRecordingMode.Stopped ) {
console.log("??? --> Stopped")
__setMode__( AudioRecordingMode.Stopped )
}

console.log("Stopped --> Playing")
_moduleMode = AudioRecordingMode.Playing;
return __emitEvent__( AudioEvent.StartedPlaying )

case AudioRecordingMode.Recording:
if (_moduleMode !== AudioRecordingMode.Stopped) {
console.log("??? --> Stopped")
__setMode__(AudioRecordingMode.Stopped)
}

console.log("Stopped --> Recording")
_moduleMode = AudioRecordingMode.Recording;
return __emitEvent__( AudioEvent.StartedRecording )
}
}

/**
* Record an audio clip
Expand All @@ -48,20 +159,21 @@ namespace codalAudio {
//% block="start recording"
//% shim=codalAudio::record
export function record(): void {
/* Dummy function */
console.log("CodalAudio -> record()")
return
__init__()
if( !isFull() )
__setMode__( AudioRecordingMode.Recording );
}

/**
* Set the sample rate for recording, playback, or both
*
* @param hz The sample rate, in Hz
*/
//% block="⚠️ set sample rate to %hz Hz || for %scope"
//% block="set sample rate to %hz Hz || for %scope"
//% expandableArgumentMode="enabled"
//% hz.defl=22000
export function setSampleRate(hz: number, scope?: AudioSampleRateScope): void {
__init__()
switch (scope) {
case AudioSampleRateScope.Everything:
_recordingFreqHz = hz;
Expand All @@ -86,7 +198,7 @@ namespace codalAudio {
//% block="set microphone gain to %gain"
//% gain.defl=Medium
export function setMicrophoneGain(gain: AudioGainEnum): void {
/* Dummy function */
__init__()
_micGain = gain;
return
}
Expand All @@ -99,8 +211,9 @@ namespace codalAudio {
//% block="​start playback"
//% shim=codalAudio::play
export function play(): void {
/* Dummy function */
console.log("CodalAudio -> play()")
__init__()
if( !isEmpty() )
__setMode__(AudioRecordingMode.Playing)
return
}

Expand All @@ -110,8 +223,8 @@ namespace codalAudio {
//% block="stop"
//% shim=codalAudio::stop
export function stop(): void {
/* Dummy function */
console.log("CodalAudio -> stop()")
__init__()
__setMode__(AudioRecordingMode.Stopped)
return
}

Expand All @@ -121,55 +234,75 @@ namespace codalAudio {
//% block="erase recording"
//% shim=codalAudio::erase
export function erase(): void {
/* Dummy function */
console.log("CodalAudio -> erase()")
__init__()
__setMode__(AudioRecordingMode.Stopped)
_memoryFill = 0
return
}

//% block="microphone gain"
export function micGain(): AudioGainEnum {
return _micGain;
return _micGain
}

//% block="recording frequency"
export function recordingHz(): number {
return _recordingFreqHz;
__init__()
return _recordingFreqHz
}

//% block="playback frequency"
export function playbackHz(): number {
return _playbackFreqHz;
__init__()
return _playbackFreqHz
}

//% block="audio duration at %hz hz"
//% shim=codalAudio::audioDiration
export function audioDuration(hz?: number): number {
return 3;
__init__()
return _memoryFill / hz
}

//% block="audio is playing"
//% shim=codalAudio::audioIsPlaying
export function audioIsPlaying(): boolean {
return false;
__init__()
return _moduleMode === AudioRecordingMode.Playing
}

//% block="audio is recording"
//% shim=codalAudio::audioIsRecording
export function audioIsRecording(): boolean {
return false;
__init__()
return _moduleMode === AudioRecordingMode.Recording
}

//% block="audio is stopped"
//% shim=codalAudio::audioIsStopped
export function audioIsStopped(): boolean {
return false;
__init__()
return _moduleMode === AudioRecordingMode.Stopped
}

//% block="⚠️ when audio %eventType"
//% block="audio buffer is full"
export function isFull(): boolean {
__init__()
return _memoryFill >= MAX_SAMPLES
}

//% block="audio buffer is empty"
export function isEmpty(): boolean {
__init__()
return _memoryFill <= 0
}

//% block="when audio %eventType"
export function audioEvent(eventType: AudioEvent, handler: () => void): void {
/* Dummy function */
console.log("CodalAudio -> audioEvent()")
return
__init__()
if( _handlers[eventType] !== undefined )
console.warn( "Just about to overwrite an existing event handler. This should never happen!" )
_handlers[eventType] = handler
}


Expand Down

0 comments on commit f711f6a

Please sign in to comment.