【问题标题】:how do i get audio files out of collection.json如何从 collection.json 中获取音频文件
【发布时间】:2017-09-29 20:38:08
【问题描述】:

如何从这个 collection.json 中获取 mp3 音频链接。 我想得到它,所以当用户在搜索框中搜索时,音频文件会弹出播放,但我有点困惑

这是我目前的代码

          const media = 'audio';
          const searchInput = document.querySelector('.search');
          const output = document.querySelector('.output')

          searchInput.addEventListener('change', searchData);

          async function searchData() {
            let search = this.value;
            const finalData = await getData(search);
            render(finalData);
          }

          function render(data) {
          	let html;
          if(media == 'image') {
             html = data.map(result => {
            	return `
            		<div class="image">
            			<img src="${result.links[0].href}"/>
            		</div>
            	`
            }).join("");
        	} else {
        		//parse the json 
                    console.log(data);
                    data.map(result => {
                      console.log(result);
                    })
                    /* i want to get the mp3 audio out of the collection.json , how do i do this please? */
                    
        	}
        	output.innerHTML = html;

          }

          function getData(search) {
            const endpoint = `https://images-api.nasa.gov/search?q=${search}&media_type=${media}`;

            return fetch(endpoint)
              .then(blob => blob.json())
              .then(data => data.collection.items);
          }
<input type="text" class="search" placeholder="planet">
<div class="output"></div>

提前谢谢你

【问题讨论】:

    标签: javascript html json api audio


    【解决方案1】:

    您只是在进行查询以获取 API 数据,它返回一组对象,每个对象仅描述一个资源。

    对于每个资源,要获取实际 MP3 的 URL,您需要在 href 字段中提供的 URL 处再次获取 collection.json 文件。这将返回该 JSON 文件的内容,在本例中是指向更多文件的 URL 数组,其中一些是 mp3。然后,您需要在该数组中找到一个以 .mp3 结尾的 URL,并将其设置为 &lt;audio&gt; 元素的 src

    【讨论】:

    • 谢谢@travellingprog 你的评论有帮助。我已经完成了第一部分,找到 .mp3 结尾的最佳方法是使用正则表达式吗?
    • 是的,你可以使用正则表达式,或者使用str.slice(-4) === '.mp3'
    • 我遇到了一些异步问题,你能帮我吗@travellingprog
    猜你喜欢
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多