ipyaudio 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,26 @@
1
+ // Copyright (c) Jupyter Development Team.
2
+ // Distributed under the terms of the Modified BSD License.
3
+
4
+ // Add any needed widget imports here (or from controls)
5
+ // import {} from '@jupyter-widgets/base';
6
+
7
+ import { createTestModel } from './utils'
8
+
9
+ import { ExampleModel } from '..'
10
+
11
+ describe('Example', () => {
12
+ describe('ExampleModel', () => {
13
+ it('should be createable', () => {
14
+ const model = createTestModel(ExampleModel)
15
+ expect(model).toBeInstanceOf(ExampleModel)
16
+ expect(model.get('value')).toEqual('Hello World')
17
+ })
18
+
19
+ it('should be createable with a value', () => {
20
+ const state = { value: 'Foo Bar!' }
21
+ const model = createTestModel(ExampleModel, state)
22
+ expect(model).toBeInstanceOf(ExampleModel)
23
+ expect(model.get('value')).toEqual('Foo Bar!')
24
+ })
25
+ })
26
+ })
__tests__/utils.ts ADDED
@@ -0,0 +1,108 @@
1
+ // Copyright (c) Jupyter Development Team.
2
+ // Distributed under the terms of the Modified BSD License.
3
+
4
+ import * as widgets from '@jupyter-widgets/base'
5
+ import * as baseManager from '@jupyter-widgets/base-manager'
6
+ import * as services from '@jupyterlab/services'
7
+
8
+ let numComms = 0
9
+
10
+ export class MockComm implements widgets.IClassicComm {
11
+ constructor() {
12
+ this.comm_id = `mock-comm-id-${numComms}`
13
+ numComms += 1
14
+ }
15
+ on_close(fn: ((x?: any) => void) | null): void {
16
+ this._on_close = fn
17
+ }
18
+ on_msg(fn: (x?: any) => void): void {
19
+ this._on_msg = fn
20
+ }
21
+ _process_msg(msg: services.KernelMessage.ICommMsgMsg): void | Promise<void> {
22
+ if (this._on_msg) {
23
+ return this._on_msg(msg)
24
+ } else {
25
+ return Promise.resolve()
26
+ }
27
+ }
28
+ close(): string {
29
+ if (this._on_close) {
30
+ this._on_close()
31
+ }
32
+ return 'dummy'
33
+ }
34
+ send(): string {
35
+ return 'dummy'
36
+ }
37
+
38
+ open(): string {
39
+ return 'dummy'
40
+ }
41
+
42
+ comm_id: string
43
+ target_name = 'dummy'
44
+ _on_msg: ((x?: any) => void) | null = null
45
+ _on_close: ((x?: any) => void) | null = null
46
+ }
47
+
48
+ export class DummyManager extends baseManager.ManagerBase {
49
+ constructor() {
50
+ super()
51
+ this.el = window.document.createElement('div')
52
+ }
53
+
54
+ display_view(msg: services.KernelMessage.IMessage, view: widgets.DOMWidgetView, options: any) {
55
+ // TODO: make this a spy
56
+ // TODO: return an html element
57
+ return Promise.resolve(view).then((view) => {
58
+ this.el.appendChild(view.el)
59
+ view.on('remove', () => console.log('view removed', view))
60
+ return view.el
61
+ })
62
+ }
63
+
64
+ protected loadClass(className: string, moduleName: string, moduleVersion: string): Promise<any> {
65
+ if (moduleName === '@jupyter-widgets/base') {
66
+ if ((widgets as any)[className]) {
67
+ return Promise.resolve((widgets as any)[className])
68
+ } else {
69
+ return Promise.reject(`Cannot find class ${className}`)
70
+ }
71
+ } else if (moduleName === 'jupyter-datawidgets') {
72
+ if (this.testClasses[className]) {
73
+ return Promise.resolve(this.testClasses[className])
74
+ } else {
75
+ return Promise.reject(`Cannot find class ${className}`)
76
+ }
77
+ } else {
78
+ return Promise.reject(`Cannot find module ${moduleName}`)
79
+ }
80
+ }
81
+
82
+ _get_comm_info() {
83
+ return Promise.resolve({})
84
+ }
85
+
86
+ _create_comm() {
87
+ return Promise.resolve(new MockComm())
88
+ }
89
+
90
+ el: HTMLElement
91
+
92
+ testClasses: { [key: string]: any } = {}
93
+ }
94
+
95
+ export interface Constructor<T> {
96
+ new (attributes?: any, options?: any): T
97
+ }
98
+
99
+ export function createTestModel<T extends widgets.WidgetModel>(constructor: Constructor<T>, attributes?: any): T {
100
+ const id = widgets.uuid()
101
+ const widget_manager = new DummyManager()
102
+ const modelOptions = {
103
+ widget_manager: widget_manager,
104
+ model_id: id,
105
+ }
106
+
107
+ return new constructor(attributes, modelOptions)
108
+ }
@@ -0,0 +1,27 @@
1
+ Copyright (c) 2025 Zhendong Peng
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions are met:
6
+
7
+ 1. Redistributions of source code must retain the above copyright notice, this
8
+ list of conditions and the following disclaimer.
9
+
10
+ 2. Redistributions in binary form must reproduce the above copyright notice,
11
+ this list of conditions and the following disclaimer in the documentation
12
+ and/or other materials provided with the distribution.
13
+
14
+ 3. Neither the name of the copyright holder nor the names of its
15
+ contributors may be used to endorse or promote products derived from
16
+ this software without specific prior written permission.
17
+
18
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,151 @@
1
+ Metadata-Version: 2.2
2
+ Name: ipyaudio
3
+ Version: 0.1.0
4
+ Summary: A Custom Jupyter Widget Library
5
+ Author-email: Zhendong Peng <pzd17@tsinghua.org.cn>
6
+ License: Copyright (c) 2025 Zhendong Peng
7
+ All rights reserved.
8
+
9
+ Redistribution and use in source and binary forms, with or without
10
+ modification, are permitted provided that the following conditions are met:
11
+
12
+ 1. Redistributions of source code must retain the above copyright notice, this
13
+ list of conditions and the following disclaimer.
14
+
15
+ 2. Redistributions in binary form must reproduce the above copyright notice,
16
+ this list of conditions and the following disclaimer in the documentation
17
+ and/or other materials provided with the distribution.
18
+
19
+ 3. Neither the name of the copyright holder nor the names of its
20
+ contributors may be used to endorse or promote products derived from
21
+ this software without specific prior written permission.
22
+
23
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
24
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
27
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
29
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
30
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
31
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33
+
34
+ Project-URL: Homepage, https://github.com/pengzhendong/ipyaudio
35
+ Keywords: IPython,Jupyter,Widgets
36
+ Classifier: Framework :: Jupyter
37
+ Classifier: Intended Audience :: Developers
38
+ Classifier: Intended Audience :: Science/Research
39
+ Classifier: License :: OSI Approved :: BSD License
40
+ Classifier: Programming Language :: Python
41
+ Classifier: Programming Language :: Python :: 3
42
+ Classifier: Programming Language :: Python :: 3.7
43
+ Classifier: Programming Language :: Python :: 3.8
44
+ Classifier: Programming Language :: Python :: 3.9
45
+ Classifier: Programming Language :: Python :: 3.10
46
+ Classifier: Programming Language :: Python :: 3.11
47
+ Classifier: Programming Language :: Python :: 3.12
48
+ Requires-Python: >=3.9
49
+ Description-Content-Type: text/markdown
50
+ License-File: LICENSE.txt
51
+ Requires-Dist: audiolab>=0.0.5
52
+ Requires-Dist: ipywidgets>=8.0.0
53
+ Requires-Dist: ipydatawidgets>=4.3.5
54
+ Provides-Extra: docs
55
+ Requires-Dist: jupyter_sphinx; extra == "docs"
56
+ Requires-Dist: nbsphinx; extra == "docs"
57
+ Requires-Dist: nbsphinx-link; extra == "docs"
58
+ Requires-Dist: pypandoc; extra == "docs"
59
+ Requires-Dist: pytest_check_links; extra == "docs"
60
+ Requires-Dist: recommonmark; extra == "docs"
61
+ Requires-Dist: sphinx>=1.5; extra == "docs"
62
+ Requires-Dist: sphinx_rtd_theme; extra == "docs"
63
+ Provides-Extra: examples
64
+ Provides-Extra: test
65
+ Requires-Dist: nbval; extra == "test"
66
+ Requires-Dist: pytest-cov; extra == "test"
67
+ Requires-Dist: pytest>=6.0; extra == "test"
68
+
69
+
70
+ # ipyaudio
71
+
72
+ [![Build Status](https://travis-ci.org/pengzhendong/ipyaudio.svg?branch=master)](https://travis-ci.org/pengzhendong/ipyaudio)
73
+ [![codecov](https://codecov.io/gh/pengzhendong/ipyaudio/branch/master/graph/badge.svg)](https://codecov.io/gh/pengzhendong/ipyaudio)
74
+
75
+
76
+ A Custom Jupyter Widget Library
77
+
78
+ ## Installation
79
+
80
+ You can install using `pip`:
81
+
82
+ ```bash
83
+ pip install ipyaudio
84
+ ```
85
+
86
+ If you are using Jupyter Notebook 5.2 or earlier, you may also need to enable
87
+ the nbextension:
88
+ ```bash
89
+ jupyter nbextension enable --py [--sys-prefix|--user|--system] ipyaudio
90
+ ```
91
+
92
+ ## Development Installation
93
+
94
+ Create a dev environment:
95
+ ```bash
96
+ conda create -n ipyaudio-dev -c conda-forge nodejs python jupyterlab=4.0.11
97
+ conda activate ipyaudio-dev
98
+ ```
99
+
100
+ Install the python. This will also build the TS package.
101
+ ```bash
102
+ pip install -e ".[test, examples]"
103
+ ```
104
+
105
+ When developing your extensions, you need to manually enable your extensions with the
106
+ notebook / lab frontend. For lab, this is done by the command:
107
+
108
+ ```
109
+ jupyter labextension develop --overwrite .
110
+ jlpm run build
111
+ ```
112
+
113
+ For classic notebook, you need to run:
114
+
115
+ ```
116
+ jupyter nbextension install --sys-prefix --symlink --overwrite --py ipyaudio
117
+ jupyter nbextension enable --sys-prefix --py ipyaudio
118
+ ```
119
+
120
+ Note that the `--symlink` flag doesn't work on Windows, so you will here have to run
121
+ the `install` command every time that you rebuild your extension. For certain installations
122
+ you might also need another flag instead of `--sys-prefix`, but we won't cover the meaning
123
+ of those flags here.
124
+
125
+ ### How to see your changes
126
+ #### Typescript:
127
+ If you use JupyterLab to develop then you can watch the source directory and run JupyterLab at the same time in different
128
+ terminals to watch for changes in the extension's source and automatically rebuild the widget.
129
+
130
+ ```bash
131
+ # Watch the source directory in one terminal, automatically rebuilding when needed
132
+ jlpm run watch
133
+ # Run JupyterLab in another terminal
134
+ jupyter lab
135
+ ```
136
+
137
+ After a change wait for the build to finish and then refresh your browser and the changes should take effect.
138
+
139
+ #### Python:
140
+ If you make a change to the python code then you will need to restart the notebook kernel to have it take effect.
141
+
142
+ ## Updating the version
143
+
144
+ To update the version, install tbump and use it to bump the version.
145
+ By default it will also create a tag.
146
+
147
+ ```bash
148
+ pip install tbump
149
+ tbump <new-version>
150
+ ```
151
+
@@ -0,0 +1,11 @@
1
+ __tests__/index.spec.ts,sha256=tgb9wfXJZURRZ8Qt4h749DsmIK6cc22OqsxpJz_XBUI,816
2
+ __tests__/utils.ts,sha256=pBou394y8EObq0tJapYIyVY8K4Fiq3syIWP4-tPEEWM,2833
3
+ wavesurfer/pcm_player.ts,sha256=ElomdQa46OHDOS2rnPc6DzvfBt3sIi7iYgBekvTQDLM,3713
4
+ wavesurfer/player.ts,sha256=Ft1jhdYPp6Der4vVMHLbH3QzKpwY-J61nSdZZxBSEbw,4599
5
+ wavesurfer/recorder.ts,sha256=VV0o3Fs-xFavTkHWP0-SWymgEvnGLSxI1v-W1K9OJeI,6083
6
+ wavesurfer/utils.ts,sha256=RH9U27IH4u1FG_Veo_2XgaZVddyW9km-a_jhl7Eddzs,4078
7
+ ipyaudio-0.1.0.dist-info/LICENSE.txt,sha256=-uZ5GSv8HIaOXcLH77MEBajSXj7X8T5N989WfkUFYKc,1498
8
+ ipyaudio-0.1.0.dist-info/METADATA,sha256=O_9S6nBES_gY2_cZU_hd45vzVu4KnaHQ7fHsXqxSQ7g,5664
9
+ ipyaudio-0.1.0.dist-info/WHEEL,sha256=jB7zZ3N9hIM9adW7qlTAyycLYW9npaWKLRzaoVcLKcM,91
10
+ ipyaudio-0.1.0.dist-info/top_level.txt,sha256=5cqDxN7ZWxG8VJmnGGQyht3YqnK_GJC07O1fgai5reo,21
11
+ ipyaudio-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.8.2)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ __tests__
2
+ wavesurfer
@@ -0,0 +1,119 @@
1
+ // Copyright (c) Zhendong Peng
2
+ // Distributed under the terms of the Modified BSD License.
3
+
4
+ import { createElement, createObjectURL } from './utils'
5
+
6
+ export class PCMPlayer {
7
+ public playButton: HTMLButtonElement
8
+ private _isDone: boolean = false
9
+ private _isPlaying: boolean = true
10
+ private _interval: number
11
+ private _samples: Int16Array = new Int16Array(0)
12
+ private _allSamples: Int16Array = new Int16Array(0)
13
+ private _audioCtx: AudioContext
14
+ private _gainNode: GainNode
15
+ private _startTime: number
16
+ private _options: { channels: number; sampleRate: number; flushTime: number; language: string }
17
+
18
+ constructor(
19
+ options?: Partial<{
20
+ channels: number
21
+ sampleRate: number
22
+ flushTime: number
23
+ language: string
24
+ }>,
25
+ ) {
26
+ this._options = Object.assign({ channels: 1, sampleRate: 16000, flushTime: 100, language: 'en' }, options)
27
+ this.playButton = createElement('button', 'btn btn-danger me-3 my-3', '<i class="fa fa-pause"></i>')
28
+ this.playButton.onclick = () => {
29
+ this._isPlaying = !this._isPlaying
30
+ this._isPlaying ? this.play() : this.pause()
31
+ this.playButton.innerHTML = `<i class="fa fa-${this._isPlaying ? 'pause' : 'play'}"></i>`
32
+ }
33
+
34
+ this._interval = window.setInterval(this.flush.bind(this), this._options.flushTime)
35
+ this._audioCtx = new (window.AudioContext || (window as any).webkitAudioContext)()
36
+ this._gainNode = this._audioCtx.createGain()
37
+ this._gainNode.gain.value = 1.0
38
+ this._gainNode.connect(this._audioCtx.destination)
39
+ this._startTime = this._audioCtx.currentTime
40
+ }
41
+
42
+ set sampleRate(rate: number) {
43
+ this._options.sampleRate = rate
44
+ }
45
+
46
+ setDone() {
47
+ this._isDone = true
48
+ }
49
+
50
+ feed(base64Data: string) {
51
+ const binaryString = atob(base64Data)
52
+ const buffer = new ArrayBuffer(binaryString.length)
53
+ const bufferView = new Uint8Array(buffer)
54
+ for (let i = 0; i < binaryString.length; i++) {
55
+ bufferView[i] = binaryString.charCodeAt(i)
56
+ }
57
+ const data = new Int16Array(buffer)
58
+ this._samples = new Int16Array([...this._samples, ...data])
59
+ this._allSamples = new Int16Array([...this._allSamples, ...data])
60
+ }
61
+
62
+ get url() {
63
+ return createObjectURL(this._allSamples.buffer, {
64
+ numChannels: this._options.channels,
65
+ sampleRate: this._options.sampleRate,
66
+ })
67
+ }
68
+
69
+ private flush() {
70
+ if (!this._samples.length) {
71
+ return
72
+ }
73
+ const isDone = this._isDone
74
+ const bufferSource = this._audioCtx.createBufferSource()
75
+ const length = this._samples.length / this._options.channels
76
+ const audioBuffer = this._audioCtx.createBuffer(this._options.channels, length, this._options.sampleRate)
77
+
78
+ for (let channel = 0; channel < this._options.channels; channel++) {
79
+ const audioData = audioBuffer.getChannelData(channel)
80
+ let offset = channel
81
+ for (let i = 0; i < length; i++) {
82
+ audioData[i] = this._samples[offset] / 32768
83
+ offset += this._options.channels
84
+ }
85
+ }
86
+
87
+ this._startTime = Math.max(this._startTime, this._audioCtx.currentTime)
88
+ bufferSource.buffer = audioBuffer
89
+ bufferSource.connect(this._gainNode)
90
+ bufferSource.start(this._startTime)
91
+ bufferSource.onended = () => {
92
+ this.playButton.disabled = isDone ? true : false
93
+ }
94
+ this._startTime += audioBuffer.duration
95
+ this._samples = new Int16Array(0)
96
+ }
97
+
98
+ async play() {
99
+ await this._audioCtx.resume()
100
+ }
101
+
102
+ async pause() {
103
+ await this._audioCtx.suspend()
104
+ }
105
+
106
+ volume(volume: number) {
107
+ this._gainNode.gain.value = volume
108
+ }
109
+
110
+ destroy() {
111
+ if (this._interval) {
112
+ clearInterval(this._interval)
113
+ }
114
+ this._samples = new Int16Array(0)
115
+ this._audioCtx.close()
116
+ }
117
+ }
118
+
119
+ export default PCMPlayer
wavesurfer/player.ts ADDED
@@ -0,0 +1,141 @@
1
+ // Copyright (c) Zhendong Peng
2
+ // Distributed under the terms of the Modified BSD License.
3
+
4
+ import WaveSurfer, { WaveSurferOptions } from 'wavesurfer.js'
5
+ import { type GenericPlugin } from 'wavesurfer.js/dist/base-plugin.js'
6
+ import HoverPlugin, { HoverPluginOptions } from 'wavesurfer.js/dist/plugins/hover.js'
7
+ import MinimapPlugin, { MinimapPluginOptions } from 'wavesurfer.js/dist/plugins/minimap.js'
8
+ import SpectrogramPlugin, { SpectrogramPluginOptions } from 'wavesurfer.js/dist/plugins/spectrogram.js'
9
+ import TimelinePlugin, { TimelinePluginOptions } from 'wavesurfer.js/dist/plugins/timeline.js'
10
+ import ZoomPlugin, { ZoomPluginOptions } from 'wavesurfer.js/dist/plugins/zoom.js'
11
+
12
+ import PCMPlayer from './pcm_player'
13
+ import { createElement, createObjectURL, formatTime } from './utils'
14
+
15
+ export interface PlayerConfig {
16
+ options: WaveSurferOptions
17
+ isStreaming: boolean
18
+ language?: string
19
+ plugins?: string[]
20
+ pluginOptions?: {
21
+ hover?: HoverPluginOptions
22
+ minimap?: MinimapPluginOptions
23
+ spectrogram?: SpectrogramPluginOptions
24
+ timeline?: TimelinePluginOptions
25
+ zoom?: ZoomPluginOptions
26
+ }
27
+ }
28
+
29
+ export default class Player {
30
+ public el: HTMLDivElement
31
+ private _container: HTMLDivElement
32
+ private _duration: HTMLDivElement
33
+ private _currentTime: HTMLDivElement
34
+ private _downloadButton: HTMLButtonElement
35
+ private _wavesurfer: WaveSurfer
36
+ private _config: PlayerConfig
37
+ // streaming
38
+ private _pcmPlayer: PCMPlayer
39
+
40
+ constructor(config: PlayerConfig) {
41
+ this.el = createElement('div', 'lm-Widget')
42
+ this._container = createElement('div', 'waveform')
43
+ this._duration = createElement('div', 'duration', '0:00')
44
+ this._currentTime = createElement('div', 'time', '0:00')
45
+ this._container.append(this._duration, this._currentTime)
46
+ this.el.append(this._container)
47
+ this._config = config
48
+ }
49
+
50
+ get url() {
51
+ if (this._config.isStreaming) {
52
+ return this._pcmPlayer.url
53
+ } else {
54
+ return createObjectURL(this._wavesurfer.getDecodedData())
55
+ }
56
+ }
57
+
58
+ set sampleRate(rate: number) {
59
+ if (this._config.isStreaming) {
60
+ this._pcmPlayer.sampleRate = rate
61
+ }
62
+ this._wavesurfer.options.sampleRate = rate
63
+ }
64
+
65
+ load(url: string) {
66
+ if (this._config.isStreaming) {
67
+ this._pcmPlayer.feed(url)
68
+ this._wavesurfer.load(this.url)
69
+ } else {
70
+ this._wavesurfer.load(url)
71
+ }
72
+ }
73
+
74
+ setDone() {
75
+ this._pcmPlayer.setDone()
76
+ }
77
+
78
+ createPCMPlayer() {
79
+ if (this._config.isStreaming) {
80
+ this._pcmPlayer = new PCMPlayer({
81
+ channels: 1,
82
+ sampleRate: this._config.options.sampleRate,
83
+ })
84
+ this.el.append(this._pcmPlayer.playButton)
85
+ }
86
+ }
87
+
88
+ createDownloadButton() {
89
+ this._downloadButton = createElement('button', 'btn btn-success my-3')
90
+ const label = this._config.language === 'zh' ? '下载' : 'Download'
91
+ this._downloadButton.innerHTML = `${label} <i class="fa fa-download"></i>`
92
+ this.el.append(this._downloadButton)
93
+ this._downloadButton.onclick = () => {
94
+ const link = document.createElement('a')
95
+ link.href = this.url
96
+ link.download = 'audio.wav'
97
+ link.click()
98
+ }
99
+ }
100
+
101
+ static createPlugins(config: PlayerConfig) {
102
+ const pluginMap = {
103
+ hover: () => HoverPlugin.create(config.pluginOptions?.hover),
104
+ minimap: () =>
105
+ MinimapPlugin.create({
106
+ ...config.pluginOptions?.minimap,
107
+ plugins: [
108
+ HoverPlugin.create({
109
+ ...config.pluginOptions?.hover,
110
+ lineWidth: 1,
111
+ }),
112
+ ],
113
+ }),
114
+ spectrogram: () => SpectrogramPlugin.create(config.pluginOptions?.spectrogram),
115
+ timeline: () => TimelinePlugin.create(config.pluginOptions?.timeline),
116
+ zoom: () => ZoomPlugin.create(config.pluginOptions?.zoom),
117
+ }
118
+ return Array.from(config.plugins ?? [])
119
+ .map((plugin) => pluginMap[plugin as keyof typeof pluginMap]?.())
120
+ .filter(Boolean) as GenericPlugin[]
121
+ }
122
+
123
+ createWaveSurfer() {
124
+ this._wavesurfer = WaveSurfer.create({
125
+ ...this._config.options,
126
+ container: this._container,
127
+ plugins: Player.createPlugins(this._config),
128
+ })
129
+ this._wavesurfer.on('interaction', () => this._wavesurfer.playPause())
130
+ this._wavesurfer.on('decode', (time) => (this._duration.textContent = formatTime(time)))
131
+ this._wavesurfer.on('timeupdate', (time) => (this._currentTime.textContent = formatTime(time)))
132
+ }
133
+
134
+ static create(config: PlayerConfig) {
135
+ const instance = new Player(config)
136
+ instance.createWaveSurfer()
137
+ instance.createPCMPlayer()
138
+ instance.createDownloadButton()
139
+ return instance
140
+ }
141
+ }
wavesurfer/recorder.ts ADDED
@@ -0,0 +1,182 @@
1
+ // Copyright (c) Zhendong Peng
2
+ // Distributed under the terms of the Modified BSD License.
3
+
4
+ import WaveSurfer, { WaveSurferOptions } from 'wavesurfer.js'
5
+ import RecordPlugin, { RecordPluginOptions } from 'wavesurfer.js/dist/plugins/record.js'
6
+
7
+ import Player, { PlayerConfig } from './player'
8
+ import { createElement, formatTime } from './utils'
9
+
10
+ interface RecorderConfig {
11
+ options: WaveSurferOptions
12
+ language?: string
13
+ recordOptions?: RecordPluginOptions
14
+ }
15
+
16
+ export default class Recorder {
17
+ public el: HTMLDivElement
18
+ private _container: HTMLDivElement
19
+ private _currentTime: HTMLDivElement
20
+ private _wavesurfer: WaveSurfer
21
+ private _config: RecorderConfig
22
+ private _recorder: RecordPlugin
23
+ private _micSelect: HTMLSelectElement
24
+ private _rateSelect: HTMLSelectElement
25
+ private _recordButton: HTMLButtonElement
26
+ private _pauseButton: HTMLButtonElement
27
+ private _player: Player
28
+
29
+ constructor(config: RecorderConfig, playerConfig: PlayerConfig) {
30
+ this.el = createElement('div', 'lm-Widget')
31
+ this._container = createElement('div', 'waveform')
32
+ this._currentTime = createElement('div', 'time', '0:00')
33
+ this._container.append(this._currentTime)
34
+ this._config = config
35
+ this._player = Player.create(playerConfig)
36
+ }
37
+
38
+ get sampleRate() {
39
+ return this._wavesurfer.options.sampleRate
40
+ }
41
+
42
+ set sampleRate(rate: number) {
43
+ this._wavesurfer.options.sampleRate = rate
44
+ this._player.sampleRate = rate
45
+ }
46
+
47
+ createWaveSurfer() {
48
+ this._wavesurfer = WaveSurfer.create({
49
+ ...this._config.options,
50
+ container: this._container,
51
+ })
52
+ }
53
+
54
+ createRateSelect() {
55
+ this._rateSelect = createElement('select', 'form-select-sm d-inline-block me-3 my-3 w-25')
56
+ const rates = [8000, 16000, 22050, 24000, 44100, 48000]
57
+ rates.forEach((rate: number) => {
58
+ const option = document.createElement('option')
59
+ option.value = rate.toString()
60
+ option.text = `${rate} Hz`
61
+ if (rate === 16000) {
62
+ option.selected = true
63
+ }
64
+ this._rateSelect.appendChild(option)
65
+ })
66
+ }
67
+
68
+ createMicSelect() {
69
+ this._micSelect = createElement('select', 'form-select-sm d-inline-block me-3 my-3 w-50')
70
+ navigator.mediaDevices
71
+ .getUserMedia({ audio: true, video: false })
72
+ .then((stream) => {
73
+ RecordPlugin.getAvailableAudioDevices().then((devices: MediaDeviceInfo[]) => {
74
+ devices.forEach((device: MediaDeviceInfo) => {
75
+ const option = document.createElement('option')
76
+ option.value = device.deviceId
77
+ option.text = device.label || device.deviceId
78
+ this._micSelect.appendChild(option)
79
+ })
80
+ })
81
+ })
82
+ .catch((err) => {
83
+ const label = this._config.language === 'zh' ? '访问麦克风失败' : 'Error accessing the microphone: '
84
+ throw new Error(label + (err as Error).message)
85
+ })
86
+ }
87
+
88
+ createPauseButton() {
89
+ this._pauseButton = createElement('button', 'btn btn-outline-danger me-3 my-3', '<i class="fa fa-pause"></i>')
90
+ this._pauseButton.disabled = true
91
+ this._pauseButton.onclick = () => {
92
+ if (this._recorder.isRecording()) {
93
+ this._recorder.pauseRecording()
94
+ this._pauseButton.innerHTML = '<i class="fa fa-play"></i>'
95
+ this._container.style.display = 'none'
96
+ this._player.el.style.display = 'block'
97
+ } else {
98
+ this._recorder.resumeRecording()
99
+ this._pauseButton.innerHTML = '<i class="fa fa-pause"></i>'
100
+ this._container.style.display = 'block'
101
+ this._player.el.style.display = 'none'
102
+ }
103
+ }
104
+ }
105
+
106
+ createRecordButton() {
107
+ this._recordButton = createElement('button', 'btn btn-danger me-3 my-3', '<i class="fa fa-microphone"></i>')
108
+ this._recordButton.onclick = () => {
109
+ if (this._recorder.isRecording() || this._recorder.isPaused()) {
110
+ this._recorder.stopRecording()
111
+ this._pauseButton.disabled = true
112
+ this._pauseButton.innerHTML = '<i class="fa fa-play"></i>'
113
+ this._recordButton.innerHTML = '<i class="fa fa-microphone"></i>'
114
+ this._container.style.display = 'none'
115
+ this._player.el.style.display = 'block'
116
+ } else {
117
+ this._wavesurfer.options.normalize = false
118
+ this.sampleRate = parseInt(this._rateSelect.value)
119
+ this._recorder.startRecording({ deviceId: this._micSelect.value }).then(() => {
120
+ this._pauseButton.disabled = false
121
+ this._pauseButton.innerHTML = '<i class="fa fa-pause"></i>'
122
+ this._recordButton.innerHTML = '<i class="fa fa-stop"></i>'
123
+ this._container.style.display = 'block'
124
+ this._player.el.style.display = 'none'
125
+ })
126
+ }
127
+ }
128
+ }
129
+
130
+ onRecordStart(callback: () => void) {
131
+ this._recorder.on('record-start', () => {
132
+ callback()
133
+ })
134
+ }
135
+
136
+ onRecordChunk(callback: (blob: Blob) => void) {
137
+ this._recorder.on('record-data-available', (blob) => {
138
+ callback(blob)
139
+ })
140
+ }
141
+
142
+ onRecordEnd(callback: (blob: Blob) => void) {
143
+ this._recorder.on('record-end', (blob) => {
144
+ this._player.load(URL.createObjectURL(blob))
145
+ callback(blob)
146
+ })
147
+ }
148
+
149
+ createRecorder() {
150
+ this._wavesurfer.toggleInteraction(false)
151
+ this._recorder = this._wavesurfer.registerPlugin(RecordPlugin.create(this._config.recordOptions))
152
+ this.createRateSelect()
153
+ this.createMicSelect()
154
+ this.createPauseButton()
155
+ this.createRecordButton()
156
+ this._container.style.display = 'none'
157
+ this._player.el.style.display = 'none'
158
+ this.el.append(
159
+ this._recordButton,
160
+ this._pauseButton,
161
+ this._rateSelect,
162
+ this._micSelect,
163
+ this._container,
164
+ this._player.el,
165
+ )
166
+
167
+ this._recorder.on('record-pause', (blob) => {
168
+ this._player.load(URL.createObjectURL(blob))
169
+ })
170
+
171
+ this._recorder.on('record-progress', (time) => {
172
+ this._currentTime.textContent = formatTime(time / 1000)
173
+ })
174
+ }
175
+
176
+ static create(config: RecorderConfig, playerConfig: PlayerConfig) {
177
+ const instance = new Recorder(config, playerConfig)
178
+ instance.createWaveSurfer()
179
+ instance.createRecorder()
180
+ return instance
181
+ }
182
+ }
wavesurfer/utils.ts ADDED
@@ -0,0 +1,137 @@
1
+ // Copyright (c) Zhendong Peng
2
+ // Distributed under the terms of the Modified BSD License.
3
+
4
+ export const createElement = <T extends HTMLElement>(
5
+ tagName: keyof HTMLElementTagNameMap,
6
+ className: string,
7
+ innerHTML: string = '',
8
+ ): T => {
9
+ const element = document.createElement(tagName) as T
10
+ element.className = className
11
+ element.innerHTML = innerHTML
12
+ return element
13
+ }
14
+
15
+ export const formatTime = (seconds: number) => {
16
+ const minutes = Math.floor(seconds / 60)
17
+ const secondsRemainder = Math.round(seconds) % 60
18
+ const paddedSeconds = `0${secondsRemainder}`.slice(-2)
19
+ return `${minutes}:${paddedSeconds}`
20
+ }
21
+
22
+ function getWavHeader(options: {
23
+ numFrames: number
24
+ numChannels?: number
25
+ sampleRate?: number
26
+ isFloat?: boolean
27
+ }): Uint8Array {
28
+ const numFrames = options.numFrames
29
+ const numChannels = options.numChannels || 2
30
+ const sampleRate = options.sampleRate || 44100
31
+ const bytesPerSample = options.isFloat ? 4 : 2
32
+ const format = options.isFloat ? 3 : 1
33
+ const blockAlign = numChannels * bytesPerSample
34
+ const byteRate = sampleRate * blockAlign
35
+ const dataSize = numFrames * blockAlign
36
+ const buffer = new ArrayBuffer(44)
37
+ const dv = new DataView(buffer)
38
+ let p = 0
39
+ function writeString(s: string) {
40
+ for (let i = 0; i < s.length; i++) {
41
+ dv.setUint8(p + i, s.charCodeAt(i))
42
+ }
43
+ p += s.length
44
+ }
45
+ function writeUint32(d: number) {
46
+ dv.setUint32(p, d, true)
47
+ p += 4
48
+ }
49
+ function writeUint16(d: number) {
50
+ dv.setUint16(p, d, true)
51
+ p += 2
52
+ }
53
+ writeString('RIFF') // ChunkID
54
+ writeUint32(dataSize + 36) // ChunkSize
55
+ writeString('WAVE') // Format
56
+ writeString('fmt ') // Subchunk1ID
57
+ writeUint32(16) // Subchunk1Size
58
+ writeUint16(format) // AudioFormat https://i.stack.imgur.com/BuSmb.png
59
+ writeUint16(numChannels) // NumChannels
60
+ writeUint32(sampleRate) // SampleRate
61
+ writeUint32(byteRate) // ByteRate
62
+ writeUint16(blockAlign) // BlockAlign
63
+ writeUint16(bytesPerSample * 8) // BitsPerSample
64
+ writeString('data') // Subchunk2ID
65
+ writeUint32(dataSize) // Subchunk2Size
66
+ return new Uint8Array(buffer)
67
+ }
68
+
69
+ function interleaveChannels(buffer: AudioBuffer): Int16Array {
70
+ const { numberOfChannels, length } = buffer
71
+ const pcmData = new Int16Array(length * numberOfChannels)
72
+ for (let channel = 0; channel < numberOfChannels; channel++) {
73
+ const data = buffer.getChannelData(channel)
74
+ const isFloat = data instanceof Float32Array
75
+ for (let i = 0; i < length; i++) {
76
+ // convert float32 to int16
77
+ pcmData[i * numberOfChannels + channel] = isFloat ? data[i] * 32767 : data[i]
78
+ }
79
+ }
80
+ return pcmData
81
+ }
82
+
83
+ function getWavBytes(
84
+ buffer: ArrayBuffer | AudioBuffer | null,
85
+ options: { numChannels: number; sampleRate: number },
86
+ ): Uint8Array {
87
+ if (!buffer) {
88
+ return new Uint8Array()
89
+ }
90
+
91
+ let headerBytes: Uint8Array
92
+ let pcmData: Uint8Array
93
+
94
+ if (buffer instanceof ArrayBuffer) {
95
+ headerBytes = getWavHeader({
96
+ isFloat: false,
97
+ numChannels: options.numChannels,
98
+ sampleRate: options.sampleRate,
99
+ numFrames: buffer.byteLength / Int16Array.BYTES_PER_ELEMENT,
100
+ })
101
+ pcmData = new Uint8Array(buffer)
102
+ } else {
103
+ headerBytes = getWavHeader({
104
+ isFloat: false,
105
+ numChannels: buffer.numberOfChannels,
106
+ sampleRate: buffer.sampleRate,
107
+ numFrames: buffer.length,
108
+ })
109
+ pcmData = new Uint8Array(interleaveChannels(buffer).buffer)
110
+ }
111
+ const wavBytes = new Uint8Array(headerBytes.length + pcmData.length)
112
+ wavBytes.set(headerBytes, 0)
113
+ wavBytes.set(pcmData, headerBytes.length)
114
+
115
+ return wavBytes
116
+ }
117
+
118
+ export const createObjectURL = (
119
+ buffer: ArrayBuffer | AudioBuffer | null,
120
+ options: { numChannels: number; sampleRate: number } = {
121
+ numChannels: 1,
122
+ sampleRate: 44100,
123
+ },
124
+ ): string => {
125
+ let wavBytes: Uint8Array
126
+
127
+ if (buffer instanceof AudioBuffer) {
128
+ wavBytes = getWavBytes(buffer, {
129
+ numChannels: buffer.numberOfChannels,
130
+ sampleRate: buffer.sampleRate,
131
+ })
132
+ } else {
133
+ wavBytes = getWavBytes(buffer, options)
134
+ }
135
+
136
+ return URL.createObjectURL(new Blob([wavBytes], { type: 'audio/wav' }))
137
+ }