【微信小程序剪辑音频】

微信小程序剪辑音频

 //点击剪辑
 clickMedia() {    
    let that = this
    let pitchOnMusicItemSrc = that.musicFilePath // 音频url // that.musicFilePath = 'www.music.mp3'
    const audioCtx = wx.createWebAudioContext()
    wx.request({
        url: pitchOnMusicItemSrc, // 音频url
        method: 'GET',
        responseType: 'arraybuffer',
        success: res => {
            audioCtx.decodeAudioData(res.data, audioBuffer => {
                const channels = audioBuffer.numberOfChannels;				        
                const rate = audioBuffer.sampleRate
                const startOffset = rate * that.audioStatrTime  //剪辑开始位置 that.audioStatrTime = 1
                const endOffset = rate * that.audioEndTime; //剪辑结束位置 that.audioStatrTime = 10
                const frameCount = endOffset - startOffset;
                const newAudioBuffer = audioCtx.createBuffer(channels,endOffset - startOffset,rate)
                const anotherArray = new Float32Array(frameCount);				        
                const offset = 0
                console.log('截取起点:',startOffset,'截取终点:',endOffset,'截取时长:',frameCount,"截取声道数:",channels)
                for (let channel = 0; channel < channels; channel++) {
                    audioBuffer.copyFromChannel(anotherArray, channel, startOffset);
                    console.log(channel,'copyFromChannel 成功')
                    newAudioBuffer.copyToChannel(anotherArray, channel, offset);
                }						
                let num = Math.trunc(frameCount)
                var fileObj = that.bufferToWave(newAudioBuffer, num);
                console.log('fileObj',fileObj)
                that.submitMusic(fileObj,frameCount)
                }, err => {
                console.error('decodeAudioData fail', err)
            })			    
        }
    })
},
//文件转buffer
bufferToWave(abuffer, len) {
        var numOfChan = abuffer.numberOfChannels,
        length = len * numOfChan * 2 + 44,
        buffer = new ArrayBuffer(length),
        view = new DataView(buffer),
        channels = [], i, sample,
        offset = 0,
        pos = 0;
        // write WAVE header
        // "RIFF"
        setUint32(0x46464952);
        // file length - 8                      
        setUint32(length - 8);
        // "WAVE"                     
        setUint32(0x45564157);
        // "fmt " chunk
        setUint32(0x20746d66);  
        // length = 16                       
        setUint32(16);  
        // PCM (uncompressed)                               
        setUint16(1); 
        setUint16(numOfChan);
        setUint32(abuffer.sampleRate);
        // avg. bytes/sec
        setUint32(abuffer.sampleRate * 2 * numOfChan);
        // block-align
        setUint16(numOfChan * 2);
        // 16-bit (hardcoded in this demo)
        setUint16(16);                           
        // "data" - chunk
        setUint32(0x61746164); 
        // chunk length                   
        setUint32(length - pos - 4);                   

        // write interleaved data
        for(i = 0; i < abuffer.numberOfChannels; i++)
            channels.push(abuffer.getChannelData(i));

        while(pos < length) {
            // interleave channels
            for(i = 0; i < numOfChan; i++) {
                // clamp
                sample = Math.max(-1, Math.min(1, channels[i][offset])); 
                // scale to 16-bit signed int
                sample = (0.5 + sample < 0 ? sample * 32768 : sample * 32767)|0; 
                // write 16-bit sample
                view.setInt16(pos, sample, true);          
                pos += 2;
            }
            // next source sample
            offset++                                     
        }

        // create Blob
        return buffer

        function setUint16(data) {
            view.setUint16(pos, data, true);
            pos += 2;
        }

        function setUint32(data) {
            view.setUint32(pos, data, true);
            pos += 4;
        }
},
//剪辑完成生成文件
submitMusic(fileObj,frameCount) {
    let that = this
        var fs = wx.getFileSystemManager();
        var number = Math.random();
        var filePath = wx.env.USER_DATA_PATH + '/music' + number + '.wav';  //文件名
        that.musicFilePath = wx.env.USER_DATA_PATH + '/music' + number + '.wav';  //文件路径赋值保存
        fs.writeFile({
            filePath: filePath,
            data:fileObj,
            encoding: 'binary',
            success: res => {
            console.log(res,filePath,frameCount,"writeFile:success") 
            //测试下载文件
            // fs.saveFile({
            // 	tempFilePath:filePath,
            // 	success:(res)=>{
            // 		console.log(res,"saveFile:success")
            // 	},
            // 	fail: err => {
            // 	  console.log(err,'saveFile:err')
            // 	}
            // })
            // wx.saveImageToPhotosAlbum({
            //   filePath: wx.env.USER_DATA_PATH + '/music' + number + '.wav',
            //   success: function (res) {
            //     wx.showToast({
            //       title: '保存成功',
            //     })
            //   },
            //   fail: function (err) {
            //     console.log(err)
            //   }
            // })
            console.log(res,"writeFile:success")
            }, fail: err => {
            console.log(err,'writeFile:err')
            }
    })	
},
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值