15 Commits

Author SHA1 Message Date
Gennady Grishkovtsov
f4bf0c503a Update version to 3.0.1 2018-12-19 01:55:08 +03:00
Gennady Grishkovtsov
4cfac6de85 Update readme 2018-12-19 01:54:47 +03:00
Gennady Grishkovtsov
685a4b76e6 Add devtool 2018-12-19 01:54:01 +03:00
Gennady Grishkovtsov
d8d3d1491e Fix HTTP headers default value 2018-12-19 01:41:36 +03:00
Gennady Grishkovtsov
db90e87dff Update version to 3.0.0
- use MP3 instead of WAV
 - new callbacks & properties
 - refactoring
2018-12-17 00:00:41 +03:00
Gennady Grishkovtsov
7e89d8a33a Update version to 2.2.0 2018-10-05 22:52:39 +03:00
Gennady Grishkovtsov
420cf2e194 Update readme 2018-10-05 22:51:55 +03:00
Gennady Grishkovtsov
52b7dfe958 Add custom header & minor refactoring 2018-10-05 22:51:41 +03:00
Gennady Grishkovtsov
5d8139d674 Update package.json & webpack 2018-10-05 22:51:20 +03:00
Gennady Grishkovtsov
206216643a Update version to 2.1.0 2018-09-30 16:01:51 +03:00
Gennady Grishkovtsov
fc0c9c824a Add record removing feature 2018-09-30 15:54:50 +03:00
Gennady Grishkovtsov
261d7a80ec Add decorator for all player buttons 2018-09-30 15:54:50 +03:00
Gennady Grishkovtsov
860f7e6158 Add random ID for each record 2018-09-30 15:54:42 +03:00
Gennady Grishkovtsov
83ccce2374 Merge pull request #1 from Tomotoes/var-fs
Add :key attribute for "v-for" to recorder.vue
2018-08-20 11:59:20 +03:00
JinmaQAQ
cb7a410ae5 Modify recorder.vue 2018-08-20 11:14:14 +08:00
23 changed files with 507 additions and 404 deletions

View File

@@ -14,8 +14,9 @@
- Records limit
- A lot of callbacks
- Individual an audio player
- MP3 support
### Tested in
### Tested in (desktop)
- Chrome
- Firefox
@@ -29,21 +30,23 @@ npm i vue-audio-recorder --save
## AudioRecorder props
| Prop | Type | Description |
| --------------------- | -------- | --------------------------------------------------------------- |
| attempts | Number | Number of recording attempts |
| compact | Boolean | Hide the download and upload buttons |
| time | Number | Time limit for the record (minutes) |
| upload-url | String | URL for uploading |
| start-record | Function | Fires after click the record button |
| stop-record | Function | Fires after click the stop button or exceeding the time limit |
| start-upload | Function | Fires after start uploading |
| attempts-limit | Function | Fires after exceeding the attempts |
| failed-upload | Function | Fires after a failure uploading |
| mic-failed | Function | Fires if your microphone doesn't work |
| successful-upload | Function | Fires after a successful uploading |
| successful-upload-msg | String | Displays the message after a successful uploading |
| failed-upload-msg | String | Displays the message after a failure uploading |
| Prop | Type | Description |
| --------------------- | -------- | ------------------------------------------------------------------------ |
| attempts | Number | Number of recording attempts |
| headers | Object | HTTP headers |
| time | Number | Time limit for the record (minutes) |
| filename | String | Download/Upload filename |
| upload-url | String | URL for uploading |
| show-download-button | Boolean | If it is true show a download button. Default: true |
| show-upload-button | Boolean | If it is true show an upload button. Default: true |
| before-upload | Function | Callback fires before uploading |
| successful-upload | Function | Callback fires after successful uploading |
| failed-upload | Function | Callback fires after failure uploading |
| mic-failed | Function | Callback fires if your microphone doesn't work |
| before-recording | Function | Callback fires after click the record button |
| pause-recording | Function | Callback fires after pause recording |
| after-recording | Function | Callback fires after click the stop button or exceeding the time limit |
| select-record | Function | Callback fires after choise a record. Returns the record |
## AudioPlayer props
| Prop | Type | Description |
@@ -52,31 +55,31 @@ npm i vue-audio-recorder --save
## Usage
The most common use case is to register the component globally
```js
import {AudioRecorder, AudioPlayer} from 'vue-audio-recorder'
Vue.component(AudioPlayer)
Vue.component(AudioRecorder)
```
Alternatively you can do this to register the components
```js
import AudioRecorder from 'vue-audio-recorder'
Vue.use(AudioRecorder)
```
```js
methods: {
callback (data) {
console.debug(data)
}
}
```
```html
<audio-recorder
upload-url="YOUR_API_URL"
:attempts="3"
:time="2"
:start-record="callback"
:stop-record="callback"
:start-upload="callback"
:headers="headers"
:before-recording="callback"
:pause-recording="callback"
:after-recording="callback"
:select-record="callback"
:before-upload="callback"
:successful-upload="callback"
:failed-upload="callback"/>
```

View File

@@ -13,9 +13,12 @@
upload-url="some url"
:attempts="3"
:time="2"
:start-record="callback"
:stop-record="callback"
:start-upload="callback"
:headers="headers"
:before-recording="callback"
:pause-recording="callback"
:after-recording="callback"
:select-record="callback"
:before-upload="callback"
:successful-upload="callback"
:failed-upload="callback"/>
@@ -24,19 +27,15 @@
</template>
<script>
import AudioPlayer from '../src/components/player'
import AudioRecorder from '../src/components/recorder'
export default {
name: 'app',
components: {
AudioPlayer,
AudioRecorder
},
data () {
return {
mp3: '/demo/example.mp3',
showRecorder: true
showRecorder: true,
headers: {
'X-Custom-Header': 'some data'
}
}
},
methods: {

View File

@@ -2,8 +2,12 @@ import Vue from 'vue'
import axios from 'axios'
import app from './app'
import AudioRecorder from '@/index'
Vue.prototype.$http = axios
Vue.use(AudioRecorder)
new Vue({
el: '#app',
render: h => h(app)

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -1,14 +1,16 @@
{
"name": "vue-audio-recorder",
"description": "Audio recorder for Vue.js. It allows to create, play, download and store records on a server",
"version": "2.0.0",
"version": "3.0.1",
"author": "Gennady Grishkovtsov <grishkovelli@gmail.com>",
"license": "MIT",
"scripts": {
"dev": "cross-env NODE_ENV=development webpack-dev-server --open --hot --https",
"build": "cross-env NODE_ENV=production webpack --progress --hide-modules"
"dev": "webpack-dev-server --env.NODE_ENV=development --mode development --open --hot --https",
"build": "webpack --env.NODE_ENV=production --mode production --progress --hide-modules"
},
"dependencies": {
"lamejs": "^1.2.0"
},
"dependencies": {},
"browserslist": [
"> 1%",
"last 2 versions",
@@ -26,11 +28,13 @@
"html-webpack-plugin": "^3.2.0",
"node-sass": "^4.5.3",
"sass-loader": "^6.0.6",
"uglifyjs-webpack-plugin": "^2.0.1",
"vue": "^2.5.16",
"vue-loader": "^13.0.5",
"vue-loader": "^14.2.2",
"vue-template-compiler": "^2.4.4",
"webpack": "^3.6.0",
"webpack-dev-server": "^2.9.1",
"webpack": "^4.17.1",
"webpack-cli": "^3.1.2",
"webpack-dev-server": "^3.1.9",
"webpack-merge": "^4.1.3"
},
"main": "dist/vue-audio-recorder.min.js",

Binary file not shown.

Before

Width:  |  Height:  |  Size: 50 KiB

After

Width:  |  Height:  |  Size: 44 KiB

View File

@@ -0,0 +1,37 @@
<style lang="scss">
@import '../scss/icons';
</style>
<template>
<icon-button
id="download"
class="ar-icon ar-icon__xs ar-icon--no-border"
name="download"
@click.native="download"/>
</template>
<script>
import IconButton from './icon-button'
export default {
props: {
record : { type: Object },
filename : { type: String }
},
components: {
IconButton
},
methods: {
download () {
if (!this.record.url) {
return
}
const link = document.createElement('a')
link.href = this.record.url
link.download = `${this.filename}.mp3`
link.click()
}
}
}
</script>

View File

@@ -24,7 +24,7 @@
</template>
<script>
import { calculateLineHeadPosition } from '@/lib/utils.js'
import { calculateLineHeadPosition } from '@/lib/utils'
export default {
props: {
@@ -35,7 +35,7 @@
},
methods: {
onMouseDown (ev) {
let seekPos = calculateLineHeadPosition(ev, this.$refs[this.refId])
const seekPos = calculateLineHeadPosition(ev, this.$refs[this.refId])
this.$emit('change-linehead', seekPos)
document.addEventListener('mousemove', this.onMouseMove)
document.addEventListener('mouseup', this.onMouseUp)
@@ -43,17 +43,17 @@
onMouseUp (ev) {
document.removeEventListener('mouseup', this.onMouseUp)
document.removeEventListener('mousemove', this.onMouseMove)
let seekPos = calculateLineHeadPosition(ev, this.$refs[this.refId])
const seekPos = calculateLineHeadPosition(ev, this.$refs[this.refId])
this.$emit('change-linehead', seekPos)
},
onMouseMove (ev) {
let seekPos = calculateLineHeadPosition(ev, this.$refs[this.refId])
const seekPos = calculateLineHeadPosition(ev, this.$refs[this.refId])
this.$emit('change-linehead', seekPos)
}
},
computed: {
calculateSize () {
let value = this.percentage < 1 ? this.percentage * 100 : this.percentage
const value = this.percentage < 1 ? this.percentage * 100 : this.percentage
return `${this.rowDirection ? 'width' : 'height'}: ${value}%`
}
}

View File

@@ -1,16 +1,26 @@
<style lang="scss">
.ar-player {
width: 380px;
height: 120px;
border: 1px solid #E8E8E8;
border-radius: 24px;
height: unset;
border: 0;
border-radius: 0;
display: flex;
flex-direction: column-reverse;
flex-direction: row;
align-items: center;
justify-content: center;
background-color: #FAFAFA;
background-color: unset;
font-family: 'Roboto', sans-serif;
& > .ar-player-bar {
border: 1px solid #E8E8E8;
border-radius: 24px;
margin: 0 0 0 5px;
& > .ar-player__progress {
width: 125px;
}
}
&-bar {
display: flex;
align-items: center;
@@ -26,33 +36,6 @@
justify-content: space-around;
}
&--compact {
height: unset;
flex-direction: row;
border: 0;
border-radius: 0;
background-color: unset;
& > .ar-player-actions {
width: unset;
& > #download,
& > #upload {
display: none;
}
}
& > .ar-player-bar {
border: 1px solid #E8E8E8;
border-radius: 24px;
margin: 0 0 0 5px;
& > .ar-player__progress {
width: 125px;
}
}
}
&__progress {
width: 160px;
margin: 0 8px;
@@ -81,27 +64,14 @@
</style>
<template>
<div class="ar-player" :class="{'ar-player--compact': compact}">
<div class="ar-player">
<div class="ar-player-actions">
<icon-button
id="download"
class="ar-icon ar-icon__sm"
name="download"
@click.native="download"/>
<icon-button
id="play"
class="ar-icon ar-icon__lg ar-player__play"
:name="playBtnIcon"
:class="{'ar-player__play--active': isPlaying}"
@click.native="playback"/>
<icon-button
id="upload"
class="ar-icon ar-icon__sm"
name="save"
@click.native="upload"/>
</div>
<div class="ar-player-bar">
@@ -120,27 +90,23 @@
</template>
<script>
import IconButton from './icon-button'
import LineControl from './line-control'
import IconButton from './icon-button'
import LineControl from './line-control'
import VolumeControl from './volume-control'
import { convertTimeMMSS } from '@/lib/utils.js'
import { convertTimeMMSS } from '@/lib/utils'
export default {
props: {
src : { type: String },
uploadUrl : { type: String },
record : { type: Object },
compact : { type: Boolean, default: true },
startUpload : { type: Function },
successfulUpload : { type: Function },
failedUpload : { type: Function }
src : { type: String },
record : { type: Object },
filename : { type: String }
},
data () {
return {
isPlaying: false,
duration: convertTimeMMSS(0),
playedTime: convertTimeMMSS(0),
progress: 0
isPlaying : false,
duration : convertTimeMMSS(0),
playedTime : convertTimeMMSS(0),
progress : 0
}
},
components: {
@@ -161,14 +127,23 @@
})
this.player.addEventListener('timeupdate', this._onTimeUpdate)
this.$eventBus.$on('remove-record', () => {
this._resetProgress()
})
},
computed: {
audioSource () {
const url = this.src || this.record.url
if (url) {
return url
} else {
this._resetProgress()
}
},
playBtnIcon () {
return this.isPlaying ? 'pause' : 'play'
},
audioSource () {
return this.src || this.record.url
},
playerUniqId () {
return `audio-player${this._uid}`
}
@@ -187,47 +162,15 @@
this.isPlaying = !this.isPlaying
},
upload () {
if (!this.audioSource) {
return
}
if (this.startUpload) {
this.startUpload()
}
this.$emit('on-start-upload')
let data = new FormData()
data.append('audio', this.record.blob, 'my-record')
this.$http.post(this.uploadUrl, data, {
headers: {'Content-Type': `multipart/form-data; boundary=${data._boundary}`}
}).then(resp => {
this.$emit('on-end-upload', 'success')
if (this.successfulUpload) {
this.successfulUpload(resp)
}
}).catch(error => {
this.$emit('on-end-upload', 'fail')
if (this.failedUpload) {
this.failedUpload(error)
}
})
},
download () {
if (!this.audioSource) {
return
}
let link = document.createElement('a')
link.href = this.record.url
link.download = 'record.wav'
link.click()
},
_resetProgress () {
this.isPlaying = false
this.progress = 0
if (this.isPlaying) {
this.player.pause()
}
this.duration = convertTimeMMSS(0)
this.playedTime = convertTimeMMSS(0)
this.progress = 0
this.isPlaying = false
},
_onTimeUpdate () {
this.playedTime = convertTimeMMSS(this.player.currentTime)

View File

@@ -23,12 +23,14 @@
&__record {
width: 320px;
height: 45px;
padding: 0 10px;
margin: 0 auto;
line-height: 45px;
display: flex;
justify-content: space-between;
border-bottom: 1px solid #E8E8E8;
position: relative;
&--selected {
border: 1px solid #E8E8E8;
@@ -70,7 +72,7 @@
&__records-limit {
position: absolute;
color: #AEAEAE;
font-size: 12px;
font-size: 13px;
top: 78px;
}
}
@@ -105,7 +107,7 @@
@keyframes blink {
0% { opacity: .2; }
20% { opacity: 1; }
20% { opacity: 1; }
100% { opacity: .2; }
}
}
@@ -144,6 +146,36 @@
color: red;
}
}
&__rm {
cursor: pointer;
position: absolute;
width: 6px;
height: 6px;
padding: 6px;
line-height: 6px;
margin: auto;
left: 10px;
bottom: 0;
top: 0;
color: rgb(244, 120, 90);
}
&__downloader,
&__uploader {
position: absolute;
top: 0;
bottom: 0;
margin: auto;
}
&__downloader {
right: 115px;
}
&__uploader {
right: 85px;
}
}
@import '../scss/icons';
@@ -152,7 +184,6 @@
<template>
<div class="ar">
<div class="ar__overlay" v-if="isUploading"></div>
<div class="ar-spinner" v-if="isUploading">
<div class="ar-spinner__dot"></div>
<div class="ar-spinner__dot"></div>
@@ -182,75 +213,98 @@
<div class="ar-records">
<div
class="ar-records__record"
:class="{'ar-records__record--selected': idx === selectedRecord.idx}"
:class="{'ar-records__record--selected': record.id === selected.id}"
:key="record.id"
v-for="(record, idx) in recordList"
@click="selectRecord(idx, record)">
@click="choiceRecord(record)">
<div
class="ar__rm"
v-if="record.id === selected.id"
@click="removeRecord(idx)">&times;</div>
<div class="ar__text">Record {{idx + 1}}</div>
<div class="ar__text">{{record.duration}}</div>
<downloader
v-if="record.id === selected.id && showDownloadButton"
class="ar__downloader"
:record="record"
:filename="filename"/>
<uploader
v-if="record.id === selected.id && showUploadButton"
class="ar__uploader"
:record="record"
:filename="filename"
:headers="headers"
:upload-url="uploadUrl"/>
</div>
</div>
<audio-player
:compact="compact"
:record="selectedRecord"
:upload-url="uploadUrl"
:start-upload="startUpload"
:successful-upload="successfulUpload"
:failed-upload="failedUpload"
@start-upload="onStartUpload"
@end-upload="onEndUpload"/>
<div :class="uploadStatusClasses" v-if="uploadStatus">{{message}}</div>
<audio-player :record="selected"/>
</div>
</div>
</template>
<script>
import AudioPlayer from './player.vue'
import IconButton from './icon-button.vue'
import Recorder from '@/lib/recorder.js'
import { convertTimeMMSS } from '@/lib/utils.js'
import AudioPlayer from './player'
import Downloader from './downloader'
import IconButton from './icon-button'
import Recorder from '@/lib/recorder'
import Uploader from './uploader'
import UploaderPropsMixin from '@/mixins/uploader-props'
import { convertTimeMMSS } from '@/lib/utils'
export default {
mixins: [UploaderPropsMixin],
props: {
attempts : { type: Number },
compact : { type: Boolean, default: false },
time : { type: Number },
uploadUrl : { type: String },
attempts : { type: Number },
time : { type: Number },
showDownloadButton : { type: Boolean, default: true },
showUploadButton : { type: Boolean, default: true },
attemptsLimit : { type: Function },
failedUpload : { type: Function },
micFailed : { type: Function },
startRecord : { type: Function },
startUpload : { type: Function },
stopRecord : { type: Function },
beforeRecording : { type: Function },
pauseRecording : { type: Function },
afterRecording : { type: Function },
failedUpload : { type: Function },
beforeUpload : { type: Function },
successfulUpload : { type: Function },
successfulUploadMsg : { type: String, default: 'Upload successful' },
failedUploadMsg : { type: String, default: 'Upload fail' }
selectRecord : { type: Function }
},
data () {
return {
isUploading: false,
recorder: new Recorder({
afterStop: () => {
this.recordList = this.recorder.recordList()
if (this.stopRecord) {
this.stopRecord('stop record')
}
},
attempts: this.attempts,
time: this.time
}),
recordList: [],
selectedRecord: {},
uploadStatus: null
isUploading : false,
recorder : this._initRecorder(),
recordList : [],
selected : {},
uploadStatus : null,
}
},
components: {
AudioPlayer,
IconButton
Downloader,
IconButton,
Uploader
},
mounted () {
this.$eventBus.$on('start-upload', () => {
this.isUploading = true
this.beforeUpload && this.beforeUpload('before upload')
})
this.$eventBus.$on('end-upload', (msg) => {
this.isUploading = false
if (msg.status === 'success') {
this.successfulUpload && this.successfulUpload(msg.response)
} else {
this.failedUpload && this.failedUpload(msg.response)
}
})
},
beforeDestroy () {
this.stopRecorder()
},
methods: {
toggleRecorder () {
@@ -260,14 +314,8 @@
if (!this.isRecording || (this.isRecording && this.isPause)) {
this.recorder.start()
if (this.startRecord) {
this.startRecord('start record')
}
} else {
this.recorder.pause()
if (this.startRecord) {
this.startRecord('pause record')
}
}
},
stopRecorder () {
@@ -276,22 +324,32 @@
}
this.recorder.stop()
this.recordList = this.recorder.recordList()
},
selectRecord (idx, record) {
this.selectedRecord = { idx: idx, url: record.url, blob: record.blob }
removeRecord (idx) {
this.recordList.splice(idx, 1)
this.$set(this.selected, 'url', null)
this.$eventBus.$emit('remove-record')
},
onStartUpload () {
this.isUploading = true
choiceRecord (record) {
if (this.selected === record) {
return
}
this.selected = record
this.selectRecord && this.selectRecord(record)
},
onEndUpload (status) {
this.isUploading = false
this.uploadStatus = status
setTimeout(() => {this.uploadStatus = null}, 1500)
_initRecorder () {
return new Recorder({
beforeRecording : this.beforeRecording,
afterRecording : this.afterRecording,
pauseRecording : this.pauseRecording,
micFailed : this.micFailed
})
}
},
computed: {
attemptsLeft () {
return this.attempts - this.recorder.records.length
return this.attempts - this.recordList.length
},
iconButtonType () {
return this.isRecording && this.isPause ? 'mic' : this.isRecording ? 'pause' : 'mic'
@@ -302,20 +360,12 @@
isRecording () {
return this.recorder.isRecording
},
message () {
return this.uploadStatus === 'success' ? this.successfulUploadMsg : this.failedUploadMsg
},
recordedTime () {
if (this.time && this.recorder.duration >= this.time * 60) {
this.stopRecorder()
}
return convertTimeMMSS(this.recorder.duration)
},
uploadStatusClasses () {
let classes = ['ar__upload-status']
classes.push(this.uploadStatus === 'success' ? 'ar__upload-status--success' : 'ar__upload-status--fail')
return classes.join(' ')
},
volume () {
return parseFloat(this.recorder.volume)
}

View File

@@ -0,0 +1,43 @@
<style lang="scss">
@import '../scss/icons';
</style>
<template>
<icon-button name="save" class="ar-icon ar-icon__xs ar-icon--no-border" @click.native="upload"/>
</template>
<script>
import IconButton from './icon-button'
import UploaderPropsMixin from '@/mixins/uploader-props'
export default {
mixins: [UploaderPropsMixin],
props: {
record: { type: Object }
},
components: {
IconButton
},
methods: {
upload () {
if (!this.record.url) {
return
}
this.$eventBus.$emit('start-upload')
const data = new FormData()
data.append('audio', this.record.blob, `${this.filename}.mp3`)
const headers = Object.assign(this.headers, {})
headers['Content-Type'] = `multipart/form-data; boundary=${data._boundary}`
this.$http.post(this.uploadUrl, data, { headers: headers }).then(resp => {
this.$eventBus.$emit('end-upload', { status: 'success', response: resp })
}).catch(error => {
this.$eventBus.$emit('end-upload', { status: 'fail', response: error })
})
}
}
}
</script>

View File

@@ -37,8 +37,8 @@
</template>
<script>
import IconButton from './icon-button.vue'
import LineControl from './line-control.vue'
import IconButton from './icon-button'
import LineControl from './line-control'
export default {
data () {

View File

@@ -1,5 +1,5 @@
import AudioPlayer from './components/player.vue'
import AudioRecorder from './components/recorder.vue'
import AudioPlayer from '@/components/player.vue'
import AudioRecorder from '@/components/recorder.vue'
const components = {
AudioPlayer,
@@ -12,6 +12,8 @@ const components = {
this.installed = true
Vue.prototype.$eventBus = Vue.prototype.$eventBus || new Vue
Vue.component('audio-player', AudioPlayer)
Vue.component('audio-recorder', AudioRecorder)
}

49
src/lib/encoder.js Normal file
View File

@@ -0,0 +1,49 @@
import { Mp3Encoder } from 'lamejs'
export default class {
constructor(config) {
this.bitRate = config.bitRate || 128
this.sampleRate = config.sampleRate || 44100
this.dataBuffer = []
this.encoder = new Mp3Encoder(1, this.sampleRate, this.bitRate)
}
encode(arrayBuffer) {
const maxSamples = 1152
const samples = this._convertBuffer(arrayBuffer)
let remaining = samples.length
for (let i = 0; remaining >= 0; i += maxSamples) {
const left = samples.subarray(i, i + maxSamples)
const buffer = this.encoder.encodeBuffer(left)
this.dataBuffer.push(new Int8Array(buffer))
remaining -= maxSamples
}
}
finish() {
this.dataBuffer.push(this.encoder.flush())
const blob = new Blob(this.dataBuffer, { type: 'audio/mp3' })
this.dataBuffer = []
return {
id : Date.now(),
blob : blob,
url : URL.createObjectURL(blob)
}
}
_floatTo16BitPCM(input, output) {
for (let i = 0; i < input.length; i++) {
const s = Math.max(-1, Math.min(1, input[i]))
output[i] = (s < 0 ? s * 0x8000 : s * 0x7FFF)
}
}
_convertBuffer(arrayBuffer) {
const data = new Float32Array(arrayBuffer)
const out = new Int16Array(arrayBuffer.length)
this._floatTo16BitPCM(data, out)
return out
}
}

View File

@@ -1,17 +1,18 @@
import WavEncoder from './wav-encoder'
import Encoder from './encoder'
import { convertTimeMMSS } from './utils'
export default class {
constructor (options = {}) {
this.afterStop = options.afterStop
this.micFailed = options.micFailed
this.beforeRecording = options.beforeRecording
this.pauseRecording = options.pauseRecording
this.afterRecording = options.afterRecording
this.micFailed = options.micFailed
this.bufferSize = 4096
this.records = []
this.samples = []
this.isPause = false
this.isRecording = false
this.isPause = false
this.isRecording = false
this.duration = 0
this.volume = 0
@@ -20,11 +21,23 @@ export default class {
}
start () {
navigator.mediaDevices.getUserMedia({audio: true})
.then(this._micCaptured.bind(this))
.catch(this._micError.bind(this))
const constraints = {
video: false,
audio: {
channelCount: 1,
echoCancellation: false
}
}
this.beforeRecording && this.beforeRecording('start recording')
navigator.mediaDevices
.getUserMedia(constraints)
.then(this._micCaptured.bind(this))
.catch(this._micError.bind(this))
this.isPause = false
this.isRecording = true
this.lameEncoder = new Encoder({})
}
stop () {
@@ -33,31 +46,17 @@ export default class {
this.processor.disconnect()
this.context.close()
let encoder = new WavEncoder({
bufferSize: this.bufferSize,
sampleRate: this.context.sampleRate,
samples: this.samples
})
const record = this.lameEncoder.finish()
record.duration = convertTimeMMSS(this.duration)
this.records.push(record)
let audioBlob = encoder.getData()
let audioUrl = URL.createObjectURL(audioBlob)
this.samples = []
this.records.push({
blob: audioBlob,
url: audioUrl,
duration: convertTimeMMSS(this.duration)
})
this.isPause = false
this.isRecording = false
this._duration = 0
this.duration = 0
this.duration = 0
if (this.afterStop) {
this.afterStop()
}
this.isPause = false
this.isRecording = false
this.afterRecording && this.afterRecording(record)
}
pause () {
@@ -68,6 +67,8 @@ export default class {
this._duration = this.duration
this.isPause = true
this.pauseRecording && this.pauseRecording('pause recording')
}
recordList () {
@@ -79,15 +80,17 @@ export default class {
}
_micCaptured (stream) {
this.context = new(window.AudioContext || window.webkitAudioContext)()
this.input = this.context.createMediaStreamSource(stream)
this.processor = this.context.createScriptProcessor(this.bufferSize, 1, 1)
this.duration = this._duration
this.stream = stream
this.context = new(window.AudioContext || window.webkitAudioContext)()
this.duration = this._duration
this.input = this.context.createMediaStreamSource(stream)
this.processor = this.context.createScriptProcessor(this.bufferSize, 1, 1)
this.stream = stream
this.processor.onaudioprocess = (ev) => {
let sample = ev.inputBuffer.getChannelData(0)
let sum = 0.0
const sample = ev.inputBuffer.getChannelData(0)
let sum = 0.0
this.lameEncoder.encode(sample)
for (let i = 0; i < sample.length; ++i) {
sum += sample[i] * sample[i]
@@ -95,7 +98,6 @@ export default class {
this.duration = parseFloat(this._duration) + parseFloat(this.context.currentTime.toFixed(2))
this.volume = Math.sqrt(sum / sample.length).toFixed(2)
this.samples.push(new Float32Array(sample))
}
this.input.connect(this.processor)
@@ -103,8 +105,6 @@ export default class {
}
_micError (error) {
if (this.micFailed) {
this.micFailed(error)
}
this.micFailed && this.micFailed(error)
}
}

View File

@@ -1,6 +1,6 @@
export function calculateLineHeadPosition (ev, element) {
let progressWidth = element.getBoundingClientRect().width
let leftPosition = ev.target.getBoundingClientRect().left
const progressWidth = element.getBoundingClientRect().width
const leftPosition = ev.target.getBoundingClientRect().left
let pos = (ev.clientX - leftPosition) / progressWidth
try {

View File

@@ -1,59 +0,0 @@
export default class {
constructor (options) {
this.bufferSize = options.bufferSize || 4096
this.sampleRate = options.sampleRate
this.samples = options.samples
}
getData () {
this._joinSamples()
let buffer = new ArrayBuffer(44 + this.samples.length * 2)
let view = new DataView(buffer)
this._writeString(view, 0, 'RIFF') // RIFF identifier
view.setUint32(4, 36 + this.samples.length * 2, true) // RIFF chunk length
this._writeString(view, 8, 'WAVE') // RIFF type
this._writeString(view, 12, 'fmt ') // format chunk identifier
view.setUint32(16, 16, true) // format chunk length
view.setUint16(20, 1, true) // sample format (raw)
view.setUint16(22, 1, true) // channel count
view.setUint32(24, this.sampleRate, true) // sample rate
view.setUint32(28, this.sampleRate * 4, true) // byte rate (sample rate * block align)
view.setUint16(32, 4, true) // block align (channel count * bytes per sample)
view.setUint16(34, 16, true) // bits per sample
this._writeString(view, 36, 'data') // data chunk identifier
view.setUint32(40, this.samples.length * 2, true) // data chunk length
this._floatTo16BitPCM(view, 44, this.samples)
return new Blob([view], {type: 'audio/wav'})
}
_floatTo16BitPCM (output, offset, input) {
for (let i = 0; i < input.length; i++, offset += 2) {
let s = Math.max(-1, Math.min(1, input[i]))
output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true)
}
}
_joinSamples () {
let recordLength = this.samples.length * this.bufferSize
let joinedSamples = new Float64Array(recordLength)
let offset = 0
for (let i = 0; i < this.samples.length; i++) {
let sample = this.samples[i]
joinedSamples.set(sample, offset)
offset += sample.length
}
this.samples = joinedSamples
}
_writeString (view, offset, string) {
for (let i = 0; i < string.length; i++) {
view.setUint8(offset + i, string.charCodeAt(i))
}
}
}

View File

@@ -0,0 +1,7 @@
export default {
props: {
filename : { type: String, default: 'record' },
headers : { type: Object, default: () => ({}) },
uploadUrl : { type: String }
}
}

View File

@@ -7,6 +7,12 @@
cursor: pointer;
transition: .2s;
&--no-border {
border: 0;
border-radius: 0;
padding: 0;
}
&--rec {
fill: white;
background-color: #FF6B64;
@@ -15,7 +21,6 @@
&--pulse {
animation: ripple .5s linear infinite;
@keyframes ripple {
0% {
box-shadow:
@@ -32,14 +37,22 @@
}
}
&__xs {
width: 18px;
height: 18px;
line-height: 18px;
}
&__sm {
width: 30px;
height: 30px;
line-height: 30px;
}
&__lg {
width: 45px;
height: 45px;
line-height: 45px;
box-shadow: 0 2px 5px 1px rgba(158,158,158,0.5);
}
}

View File

@@ -1,67 +1,70 @@
const webpack = require('webpack')
const merge = require('webpack-merge')
const env = `./webpack.${process.env.NODE_ENV === 'production' ? 'prod' : 'dev'}.js`
const path = require('path')
module.exports = merge(require(env), {
module: {
rules: [
{
test: /\.scss$/,
use: [
'vue-style-loader',
'css-loader',
'sass-loader'
],
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
'scss': [
'vue-style-loader',
'css-loader',
'sass-loader'
]
module.exports = (env, args) => {
let conf = `./webpack.${env.NODE_ENV === 'production' ? 'prod' : 'dev'}.js`
return merge(require(conf), {
module: {
rules: [
{
test: /\.scss$/,
use: [
'vue-style-loader',
'css-loader',
'sass-loader'
],
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
'scss': [
'vue-style-loader',
'css-loader',
'sass-loader'
]
}
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}
]
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': path.resolve(__dirname, 'src')
]
},
extensions: ['*', '.js', '.vue', '.json']
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: `"${process.env.NODE_ENV}"`
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': path.resolve(__dirname, 'src')
},
VERSION: JSON.stringify(require("./package.json").version)
}),
],
devServer: {
historyApiFallback: true,
noInfo: true,
overlay: true
},
performance: {
hints: false
}
})
extensions: ['*', '.js', '.vue', '.json']
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: `"${process.env.NODE_ENV}"`
},
VERSION: JSON.stringify(require("./package.json").version)
}),
],
devServer: {
historyApiFallback: true,
noInfo: true,
overlay: true
},
performance: {
hints: false
}
})
}

View File

@@ -2,7 +2,6 @@ const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
devtool: '#eval-source-map',
entry: './demo/index.js',
output: {
path: path.resolve(__dirname, './demo')

View File

@@ -1,9 +1,12 @@
const path = require('path')
const webpack = require('webpack')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
module.exports = {
devtool: '#source-map',
entry: './src/index.js',
entry: {
main: './src/index.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'vue-audio-recorder.min.js',
@@ -12,18 +15,21 @@ module.exports = {
libraryExport: 'default',
umdNamedDefine: true
},
optimization: {
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true,
sourceMap: true
})
]
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: true
}
}),
new webpack.LoaderOptionsPlugin({
minimize: false
})