2015-05-15 1 views
0

Сегодня я добавил способ, позволяющий пользователям использовать музыку soundcloud на веб-сайте, за исключением того, что он работает только при удалении анализатора, сгенерированного веб-аудио api.soundcloud api и веб-аудио api не работают вместе

вот код, который добавляет ссылку SoundCloud к аудио тэгам:

$(document).keydown(function(e){ 
    if (e.which == 13 && $("#customSong").is(":focus")){ 
     var customSongLink = $("#customSong").val(); 

     SC.get('/resolve', { url: customSongLink }, function(sound) { 
      SC.get("/tracks/" + sound.id, {}, function(sound){ 
       $("#Musique").attr("src", sound.uri+"/stream?client_id=MY_CLIENT_ID"); 

       $(".mediaName").html("<span></span>"); 
       $(".mediaName span").html(sound.user.username+" - "+sound.title); 
       $(".mediaName").textfill(); 
      }); 
     }); 
    } 
}); 

и вот код для визуализатора:

var canvas, ctx, source, context, analyser, fbc_array, bar_x, bar_height; 
function initVisualizer() { 
    context = new AudioContext(); 
    analyser = context.createAnalyser(); 
    biquad = context.createBiquadFilter(); 
    gainNode = context.createGain(); 
    canvas = document.getElementById("visualizer"); 
    ctx = canvas.getContext('2d'); 
    ctx.fillStyle = "#3f3f3f"; 


    analyser.smoothingTimeConstant = 0.8; 
    biquad.frequency.value = 15000; 
    gainNode.gain.value = 1; 

    source = context.createMediaElementSource(Musique); 
    source.connect(biquad); 
    biquad.connect(gainNode); 
    gainNode.connect(analyser); 
    analyser.connect(context.destination); 

    $("#frequencyNumber").html(biquad.frequency.value); 
    $("#visualizerSensibilityNumber").html(analyser.smoothingTimeConstant); 
    $("#gainNumber").html(gainNode.gain.value.toPrecision(3)); 

    framelooper() 
} 

function framelooper() { 
    window.requestAnimationFrame(framelooper); 
    fbcArray = new Uint8Array(analyser.frequencyBinCount); 
    analyser.getByteFrequencyData(fbcArray); 
    ctx.clearRect(0, 0, canvas.width, canvas.height); 
    for (i=0; i < bars; i++) { 
     bar_x = i * bar_x_spaces + 0.5; 
     bar_height = -(fbcArray[i]/bar_height_sensibility); 

     if (visualizerStyle == 1){ 
      //Simple 
      ctx.fillRect(bar_x, canvas.height, bar_width, bar_height); 
      $("#visualizerStyleType").html("Simple"); 
     } 
     else if (visualizerStyle == 2) { 
      //Reflection 
      ctx.fillRect(bar_x, canvas.height/2, bar_width, bar_height/2); 
      ctx.fillRect(bar_x, canvas.height/2, bar_width, -bar_height/2); 
      $("#visualizerStyleType").html("Reflection"); 
     } 
     else { 
      //Two-faced 
      ctx.fillRect(0, bar_x, -bar_height, bar_width); 
      ctx.fillRect(canvas.width, bar_x, bar_height, bar_width); 
      $("#visualizerStyleType").html("Face to Face"); 
     } 
    } 
} 

website with the issue (double click on the song title to make the input box appear, enter a soundcloud link inside)

Edit: я узнал, что проблема связана с изменением перекрестного происхождения аудиофайлов, я также видел, как многие люди говорят, что добавление «crossOrigin = ano nymous "исправляет это, но это не для меня.

делает это только для музыки, или это уже не возможно исправить?

Если это позже, есть ли какие-либо другие исправления?

+0

это просто куча файлов я загруженные на Google диск, так что я не могу сделать это –

ответ

0

Вам не нужно устанавливать crossOrigin. Сервер также должен разрешать доступ к кросс-контенту, возвращая соответствующие заголовки. Это, вероятно, не под вашим контролем.

+0

как бы вы это, просто чтобы быть уверенным –

+0

Вы должны спросить SoundCloud о что. –

0

Похоже, что без SDK и без createMediaElementSource он будет работать.

То, как я загружаю образец из SoundCloud.

function SCkickOffSampleDownload(sample) { 
    var url = new URL(sample+ '?client_id=679877a8ddb9badc6a2a75373c5f3de7'); 
    var request = new XMLHttpRequest(); 
    request.open("GET", url, true); 
    request.responseType = "arraybuffer"; 
    request.onload = function() { 
     audioContext.decodeAudioData(request.response, 
     function(buffer) { 
      console.log("sample loaded!"); 
      sample.loaded=true; 
      source.buffer = buffer; 
      source.start(0); 
      initVisualizer();   
     }, 
     function() { console.log("Decoding error! ");}); 
    } 
    sample.loaded = false; 
    request.send(); 
    } 

Вот скрипку почти код:

http://jsfiddle.net/iambnz/8qw5511L/

EDIT 1:

$(function() { 
SC.initialize({ 
    client_id: "679877a8ddb9badc6a2a75373c5f3de7" 
    }); 

var scurl = 'https://soundcloud.com/bnzlovesyou/daktari-preview'; 
var canvas, ctx, source, context, analyser, fbc_array, bar_x, bar_height; 
var visualizerColor = "#3f3f3f"; 
var bars = 50; 
var bar_x_spaces = 6; 
var bar_width = 4; 
var bar_height_sensibility = 1.75; 
var visualizerStyle = 1; 

audioContext = new AudioContext(); 
var source = audioContext.createBufferSource(); 
var gainNode = audioContext.createGain(); 
source.connect(gainNode); 
gainNode.gain.value = 0.5; 

function SCkickOffSampleDownload(sample) { 
    var url = new URL(sample+ '?client_id=679877a8ddb9badc6a2a75373c5f3de7'); 
    var request = new XMLHttpRequest(); 
    request.open("GET", url, true); 
    request.responseType = "arraybuffer"; 
    request.onload = function() { 
     audioContext.decodeAudioData(request.response, 
     function(buffer) { 
      console.log("sample loaded!"); 
      sample.loaded=true; 
      source.buffer = buffer; 
      source.start(0); 
      initVisualizer();   
     }, 
     function() { console.log("Decoding error! ");}); 
    } 
    sample.loaded = false; 
    request.send(); 
    } 

function initVisualizer() { 
// context = new AudioContext(); 
    analyser = audioContext.createAnalyser(); 
    biquad = audioContext.createBiquadFilter(); 
    gainNode = audioContext.createGain(); 
    canvas = document.getElementById("visualizer"); 
    ctx = canvas.getContext("2d"); 
    ctx.fillStyle = "#3f3f3f"; 


    analyser.smoothingTimeConstant = 0.8; 
    biquad.frequency.value = 15000; 
    gainNode.gain.value = 1; 

    source.connect(biquad); 
    biquad.connect(gainNode); 
    gainNode.connect(analyser); 
    analyser.connect(audioContext.destination); 

    $("#frequencyNumber").html(biquad.frequency.value); 
    $("#visualizerSensibilityNumber").html(analyser.smoothingTimeConstant); 
    $("#gainNumber").html(gainNode.gain.value.toPrecision(3)); 

    framelooper() 
} 

function framelooper() { 
    window.requestAnimationFrame(framelooper); 
    fbcArray = new Uint8Array(analyser.frequencyBinCount); 
    analyser.getByteFrequencyData(fbcArray); 
    ctx.clearRect(0, 0, canvas.width, canvas.height); 
    for (i=0; i < bars; i++) { 
     bar_x = i * bar_x_spaces + 0.5; 
     bar_height = -(fbcArray[i]/bar_height_sensibility); 

     if (visualizerStyle == 1){ 
      //Simple 
      ctx.fillRect(bar_x, canvas.height, bar_width, bar_height); 
      $("#visualizerStyleType").html("Simple"); 
     } 
     else if (visualizerStyle == 2) { 
      //Reflection 
      ctx.fillRect(bar_x, canvas.height/2, bar_width, bar_height/2); 
      ctx.fillRect(bar_x, canvas.height/2, bar_width, -bar_height/2); 
      $("#visualizerStyleType").html("Reflection"); 
     } 
     else { 
      //Two-faced 
      ctx.fillRect(0, bar_x, -bar_height, bar_width); 
      ctx.fillRect(canvas.width, bar_x, bar_height, bar_width); 
      $("#visualizerStyleType").html("Face to Face"); 
     } 
    } 
} 


SC.get('/resolve', { url: scurl }, function(sound) { 
     SCkickOffSampleDownload(sound.stream_url); 
     }); 

}); 

рабочий пример, который SoundCloud и WebAudio апи работать вместе. Я взял файлы с вашего диска.

http://jsfiddle.net/iambnz/e3zxby88/

+0

У меня есть код o google drive, и я получаю эту ошибку: заголовок «Нет» Access-Control-Allow-Origin присутствует на запрошенном ресурсе. Поэтому «https://5a0409b6129ff21bdaa69aae95690807eb6e5482.googledrive.com» не разрешен доступ «. –

+0

у вас пробовали код? вот скрипка на диске: https://googledrive.com/host/0B0TM6mPwlvfkQ0RkeHZXN3Flek0 – devbnz

+0

yup, на сайте, когда вы вводите ссылку в поле ввода и нажимаете enter, она дает эту ошибку в консоли, это то, что customSong .js выглядит следующим образом: http://pastebin.com/JKk63EWt –

Смежные вопросы