gpt4 book ai didi

java - 使用 Java 托管 MP3 文件

转载 作者:可可西里 更新时间:2023-11-01 17:17:08 27 4
gpt4 key购买 nike

所以我正在尝试模拟类似该站点设置的内容:

http://www.ntonyx.com/mp3files/Morning_Flower.mp3

当像 chrome 这样的浏览器转到这个确切的 url 时,基本上会出现一个播放器,您可以“播放”音乐。

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class WebServer {

public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/test/file.mp3", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}

static class MyHandler implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {
String response = "This is the response";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}

}

我正在尝试用一些简单的 Java 代码来模拟它。我正在努力弄清楚我应该如何格式化以这种方式出现的请求。有没有办法将存储在我的驱动器上的本地文件发送到请求?我一直在努力寻找如何执行此操作的示例

最佳答案

您可以使用 FileInputStream 读取文件的字节以发送到浏览器:

import java.io.IOException;
import java.io.OutputStream;
import java.io.FileInputStream;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class WebServer {

public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/test/file.mp3", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}

static class MyHandler implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {

File file = new File("path/to/file.mp3"); // Create a new File object pointing to your mp3 file

/* https://stackoverflow.com/questions/38679686/ :) */
t.getResponseHeaders().put("Content-Type", "audio/mpeg"); // Make sure the browser knows this is an audio file
t.sendResponseHeaders(200, file.length()); // Send the length of the file to the browser

FileInputStream stream = new FileInputStream(file); // Open an InputStream to read your file
OutputStream os = t.getResponseBody();
byte[] buff = new byte[1024]; // Create a small buffer to hold bytes as you read them
int read = 0; // Keep track of how many bytes you read

// While there are still bytes to read, send them to the client
while((read = stream.read(buff)) > 0) {
os.write(buff, 0, read);
}
// Close the streams
os.close();
stream.close();
}
}

}

关于java - 使用 Java 托管 MP3 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55928382/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com