Skip to content
This repository has been archived by the owner on Sep 8, 2024. It is now read-only.

Commit

Permalink
feat(audio): 50% completed
Browse files Browse the repository at this point in the history
  • Loading branch information
sheepbox8646 committed Jul 31, 2024
1 parent c33b095 commit af69602
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 0 deletions.
57 changes: 57 additions & 0 deletions packages/basic/src/widgets/audioPlayer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import type { WidgetOptions, WidgetStyle } from '@newcar/core'
import { Widget } from '@newcar/core'

export interface AudioPlayerOptions extends WidgetOptions {
style: AudioPlayerStyle
}

export interface AudioPlayerStyle extends WidgetStyle {}

export interface AudioItem {
duration: number
file: ArrayBuffer | number
}

export class AudioPlayer extends Widget {
private context: AudioContext
private tracks: Array<AudioTrack>

constructor(options: AudioPlayerOptions) {
super(options)

this.context = new AudioContext()
}

play() {
// TODO
}

createTrack(): AudioTrack {
const result = new AudioTrack(this.context)
this.tracks.push(result)

return result
}
}

export class AudioTrack {
source: AudioBufferSourceNode
items: Array<AudioItem> = []

constructor(context: AudioContext) {
this.source = context.createBufferSource()
this.source.connect(this.source.context.destination)
}

add(audio: ArrayBuffer | number, duration?: number) {
this.items.push({
file: audio,
duration,
})
return this
}

play() {
this.source.start()
}
}
26 changes: 26 additions & 0 deletions packages/core/src/apis/use-audio.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { $source } from '../global'

/**
* Preloading a font file.
* @param src The font file's path.
* @returns The Font with `ArrayBuffer` type.
*/
export async function useFont(src: string) {
if (typeof window !== 'undefined') {
const response = await fetch(src)
const array = await response.arrayBuffer()
$source.fonts.push(array)
return array
}
else {
const fs = await import('node:fs')
const path = await import('node:path')
const buffer = fs.readFileSync(path.resolve(src))
const array = buffer.buffer.slice(
buffer.byteOffset,
buffer.byteOffset + buffer.byteLength,
)
$source.fonts.push(array)
return array
}
}

0 comments on commit af69602

Please sign in to comment.