我试图发挥一个bas64编码的mp3使用Angular 和 typescript

vwkv1x7d  于 2023-06-24  发布在  TypeScript
关注(0)|答案(1)|浏览(124)

我正在尝试以Angular 播放bas64编码的mp3。我有一个byteArray,然后我将其转换为base64。我不认为这个字节数组是损坏的,因为当我转换它并将base64字符串放在stackblitz https://stackblitz.com/edit/angular-audio-blob-rce4y1?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.ts上时,文件转换和播放没有问题。在下面的代码中,我得到一个错误“ERROR DOMException:无法在“窗口”上执行“atob”“
我的Tyepscript方法调用我的控制器端点从byteArray检索转换后的base 64。

export class MediaPlayComponent {
@ViewChild('audioTag') audioTag:ElementRef;
audioSource = '';
if(fileExtension == 'mp3')
{
this.testService.getUrl(`fileEndpoint-file/${doc.id}/source`)
    .subscribe((data) => {
        console.log("Data log below");
        console.log(data);
         data ='audio/ogg;base64,' + data; 
         var binary= this.convertDataURIToBinary(data);
         var blob = new Blob([binary], {type : 'audio/mp3'});
         var blobUrl = URL.createObjectURL(blob);
         this.audioSource = blobUrl;
         console.log("blob below");
         console.log(blobUrl);
         //this.audioTag.nativeElement.setAttribute('src',this.audioSource);
         console.log("Audio" + this.audioSource);

      })
}

 convertDataURIToBinary(dataURI) {
    console.log("URI Below"); 
    console.log(dataURI); 
    var BASE64_MARKER = ';base64,';
    var base64Index = dataURI.toString().indexOf(BASE64_MARKER) + BASE64_MARKER.length;
    var base64 = dataURI.toString().substring(base64Index);
    var raw = window.atob(decodeURIComponent(base64));
    var rawLength = raw.length;
    var array = new Uint8Array(new ArrayBuffer(rawLength));

    for(var i = 0; i < rawLength; i++) {
      array[i] = raw.charCodeAt(i);
    }
    return array;
}

HTML

<audio [src]="audioSource | safe:'url'" id="audio"  controls #audioTag></audio>
mefy6pfw

mefy6pfw1#

请使用缓冲库,因为window.atob已被弃用

// import library
import { Buffer } from "buffer";

// define data
const b64 = "SGVsbG8sIFdvcmxkIQ==";
const str = 'Hello, World!'

// define conversion functions
const decode = (str: string):string => Buffer.from(str, 'base64').toString('binary');
const encode = (str: string):string => Buffer.from(str, 'binary').toString('base64');

// use functions
let decodedData = decode(b64);
let encodedData = decode(decodedData);

相关问题