当前位置: 首页 > news >正文

播放Samba协议下的音视频文件

Samba(也被称为SMB/CIFS)是一个用于在局域网内共享文件和打印服务的协议,广泛应用于Windows和Linux系统之间的文件共享。

一、展示Samba服务器下的文件

使用如jcifs这样的Java库来在安卓应用中集成SMB/CIFS客户端功能。这个库提供了与SMB/CIFS服务器进行通信的API,允许在安卓应用中直接访问共享文件。

代码实现 :

NtlmPasswordAuthentication auth =new NtlmPasswordAuthentication(SambaManager.getDomainName(path), "zhanghao", "mima");
SmbFile file = new SmbFile("smb://172.16.1.94/", auth); 
//根路径 smb://172.16.1.94/
//循环遍历即可                      

二、尝试使用MediaPlayer播放

代码如下

// MediaPlayer.java
String uri = "smb://172.16.1.73/lyg/newtestsamb/._Stay_With_Me 新郎入场.mp3";
mstarPlayer.setDataSource(context, uri);

报错文件解析错误,经排查原生的Android MediaPlayer不直接支持通过SMB协议访问和播放文件,因为它主要是为本地存储和网络流媒体设计的。

三、转成HTTP流播放

代码如下

public abstract class StreamServer {// ==================================================// API parts// ==================================================/*** Override this to customize the server.<p>* <p>* (By default, this delegates to serveFile() and allows directory listing.)** @param uri    Percent-decoded URI without parameters, for example "/index.cgi"* @param method "GET", "POST" etc.* @param parms  Parsed, percent decoded parameters from URI and, in case of POST, data.* @param header Header entries, percent decoded* @return HTTP response, see class Response for details*/public abstract Response serve(String uri, String method, Properties header, Properties parms, Properties files);/*** HTTP response.* Return one of these from serve().*/public class Response {/*** Default constructor: response = HTTP_OK, data = mime = 'null'*/public Response() {this.status = HTTP_OK;}/*** Basic constructor.*/public Response(String status, String mimeType, StreamSource data) {this.status = status;this.mimeType = mimeType;this.data = data;}/*** Convenience method that makes an InputStream out of* given text.*//*** Adds given line to the header.*/public void addHeader(String name, String value) {header.put(name, value);}/*** HTTP status code after processing, e.g. "200 OK", HTTP_OK*/public String status;/*** MIME type of content, e.g. "text/html"*/public String mimeType;/*** Data of the response, may be null.*/public StreamSource data;/*** Headers for the HTTP response. Use addHeader()* to add lines.*/public Properties header = new Properties();}/*** Some HTTP response status codes*/public static final StringHTTP_OK = "200 OK",HTTP_PARTIALCONTENT = "206 Partial Content",HTTP_RANGE_NOT_SATISFIABLE = "416 Requested Range Not Satisfiable",HTTP_REDIRECT = "301 Moved Permanently",HTTP_FORBIDDEN = "403 Forbidden",HTTP_NOTFOUND = "404 Not Found",HTTP_BADREQUEST = "400 Bad Request",HTTP_INTERNALERROR = "500 Internal Server Error",HTTP_NOTIMPLEMENTED = "501 Not Implemented";/*** Common mime types for dynamic content*/public static final StringMIME_PLAINTEXT = "text/plain",MIME_HTML = "text/html",MIME_DEFAULT_BINARY = "application/octet-stream",MIME_XML = "text/xml";// ==================================================// Socket & server code// ==================================================/*** Starts a HTTP server to given port.<p>* Throws an IOException if the socket is already in use*///private HTTPSession session;public StreamServer(int port, File wwwroot) throws IOException {myTcpPort = port;this.myRootDir = wwwroot;myServerSocket = new ServerSocket(myTcpPort);myThread = new Thread(() -> {try {while (true) {Socket accept = myServerSocket.accept();new HTTPSession(accept);}} catch (IOException ioe) {}});myThread.setDaemon(true);myThread.start();}/*** Stops the server.*/public void stop() {try {myServerSocket.close();myThread.join();} catch (IOException ioe) {} catch (InterruptedException e) {}}/*** Handles one session, i.e. parses the HTTP request* and returns the response.*/private class HTTPSession implements Runnable {private InputStream is;private final Socket socket;public HTTPSession(Socket s) {socket = s;//mySocket = s;Thread t = new Thread(this);t.setDaemon(true);t.start();}public void run() {try {//openInputStream();handleResponse(socket);} finally {if (is != null) {try {is.close();socket.close();} catch (IOException e) {e.printStackTrace();}}}}private void handleResponse(Socket socket) {try {is = socket.getInputStream();if (is == null) return;// Read the first 8192 bytes.// The full header should fit in here.// Apache's default header limit is 8KB.int bufsize = 8192;byte[] buf = new byte[bufsize];int rlen = is.read(buf, 0, bufsize);if (rlen <= 0) return;// Create a BufferedReader for parsing the header.ByteArrayInputStream hbis = new ByteArrayInputStream(buf, 0, rlen);BufferedReader hin = new BufferedReader(new InputStreamReader(hbis, "utf-8"));Properties pre = new Properties();Properties parms = new Properties();Properties header = new Properties();Properties files = new Properties();// Decode the header into parms and header java propertiesdecodeHeader(hin, pre, parms, header);Log.d("Explorer", pre.toString());Log.d("Explorer", "Params: " + parms.toString());Log.d("Explorer", "Header: " + header.toString());String method = pre.getProperty("method");String uri = pre.getProperty("uri");long size = 0x7FFFFFFFFFFFFFFFl;String contentLength = header.getProperty("content-length");if (contentLength != null) {try {size = Integer.parseInt(contentLength);} catch (NumberFormatException ex) {}}// We are looking for the byte separating header from body.// It must be the last byte of the first two sequential new lines.int splitbyte = 0;boolean sbfound = false;while (splitbyte < rlen) {if (buf[splitbyte] == '\r' && buf[++splitbyte] == '\n' && buf[++splitbyte] == '\r' && buf[++splitbyte] == '\n') {sbfound = true;break;}splitbyte++;}splitbyte++;// Write the part of body already read to ByteArrayOutputStream fByteArrayOutputStream f = new ByteArrayOutputStream();if (splitbyte < rlen) f.write(buf, splitbyte, rlen - splitbyte);// While Firefox sends on the first read all the data fitting// our buffer, Chrome and Opera sends only the headers even if// there is data for the body. So we do some magic here to find// out whether we have already consumed part of body, if we// have reached the end of the data to be sent or we should// expect the first byte of the body at the next read.if (splitbyte < rlen)size -= rlen - splitbyte + 1;else if (!sbfound || size == 0x7FFFFFFFFFFFFFFFl)size = 0;// Now read all the body and write it to fbuf = new byte[512];while (rlen >= 0 && size > 0) {rlen = is.read(buf, 0, 512);size -= rlen;if (rlen > 0)f.write(buf, 0, rlen);}// Get the raw body as a byte []byte[] fbuf = f.toByteArray();// Create a BufferedReader for easily reading it as string.ByteArrayInputStream bin = new ByteArrayInputStream(fbuf);BufferedReader in = new BufferedReader(new InputStreamReader(bin));// If the method is POST, there may be parameters// in data section, too, read it:if (method.equalsIgnoreCase("POST")) {String contentType = "";String contentTypeHeader = header.getProperty("content-type");StringTokenizer st = new StringTokenizer(contentTypeHeader, "; ");if (st.hasMoreTokens()) {contentType = st.nextToken();}if (contentType.equalsIgnoreCase("multipart/form-data")) {// Handle multipart/form-dataif (!st.hasMoreTokens())sendError(socket, HTTP_BADREQUEST, "BAD REQUEST: Content type is multipart/form-data but boundary missing. Usage: GET /example/file.html");String boundaryExp = st.nextToken();st = new StringTokenizer(boundaryExp, "=");if (st.countTokens() != 2)sendError(socket, HTTP_BADREQUEST, "BAD REQUEST: Content type is multipart/form-data but boundary syntax error. Usage: GET /example/file.html");st.nextToken();String boundary = st.nextToken();decodeMultipartData(boundary, fbuf, in, parms, files);} else {// Handle application/x-www-form-urlencodedString postLine = "";char pbuf[] = new char[512];int read = in.read(pbuf);while (read >= 0 && !postLine.endsWith("\r\n")) {postLine += String.valueOf(pbuf, 0, read);read = in.read(pbuf);if (Thread.interrupted()) {throw new InterruptedException();}}postLine = postLine.trim();decodeParms(postLine, parms);}}// Ok, now do the serve()Response r = serve(uri, method, header, parms, files);if (r == null)sendError(socket, HTTP_INTERNALERROR, "SERVER INTERNAL ERROR: Serve() returned a null response.");elsesendResponse(socket, r.status, r.mimeType, r.header, r.data);in.close();} catch (IOException ioe) {try {sendError(socket, HTTP_INTERNALERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());} catch (Throwable t) {}} catch (InterruptedException ie) {// Thrown by sendError, ignore and exit the thread.}}/*** Decodes the sent headers and loads the data into* java Properties' key - value pairs**/private void decodeHeader(BufferedReader in, Properties pre, Properties parms, Properties header)throws InterruptedException {try {// Read the request lineString inLine = in.readLine();if (inLine == null) return;StringTokenizer st = new StringTokenizer(inLine);if (!st.hasMoreTokens())sendError(socket, HTTP_BADREQUEST, "BAD REQUEST: Syntax error. Usage: GET /example/file.html");String method = st.nextToken();pre.put("method", method);if (!st.hasMoreTokens())sendError(socket, HTTP_BADREQUEST, "BAD REQUEST: Missing URI. Usage: GET /example/file.html");String uri = st.nextToken();// Decode parameters from the URIint qmi = uri.indexOf('?');if (qmi >= 0) {decodeParms(uri.substring(qmi + 1), parms);uri = decodePercent(uri.substring(0, qmi));} else uri = Uri.decode(uri);//decodePercent(uri);if (st.hasMoreTokens()) {String line = in.readLine();while (line != null && line.trim().length() > 0) {int p = line.indexOf(':');if (p >= 0)header.put(line.substring(0, p).trim().toLowerCase(), line.substring(p + 1).trim());line = in.readLine();}}pre.put("uri", uri);} catch (IOException ioe) {sendError(socket, HTTP_INTERNALERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());}}/*** Decodes the Multipart Body data and put it* into java Properties' key - value pairs.**/private void decodeMultipartData(String boundary, byte[] fbuf, BufferedReader in, Properties parms, Properties files)throws InterruptedException {try {int[] bpositions = getBoundaryPositions(fbuf, boundary.getBytes());int boundarycount = 1;String mpline = in.readLine();while (mpline != null) {if (mpline.indexOf(boundary) == -1)sendError(socket, HTTP_BADREQUEST, "BAD REQUEST: Content type is multipart/form-data but next chunk does not start with boundary. Usage: GET /example/file.html");boundarycount++;Properties item = new Properties();mpline = in.readLine();while (mpline != null && mpline.trim().length() > 0) {int p = mpline.indexOf(':');if (p != -1)item.put(mpline.substring(0, p).trim().toLowerCase(), mpline.substring(p + 1).trim());mpline = in.readLine();}if (mpline != null) {String contentDisposition = item.getProperty("content-disposition");if (contentDisposition == null) {sendError(socket, HTTP_BADREQUEST, "BAD REQUEST: Content type is multipart/form-data but no content-disposition info found. Usage: GET /example/file.html");}StringTokenizer st = new StringTokenizer(contentDisposition, "; ");Properties disposition = new Properties();while (st.hasMoreTokens()) {String token = st.nextToken();int p = token.indexOf('=');if (p != -1)disposition.put(token.substring(0, p).trim().toLowerCase(), token.substring(p + 1).trim());}String pname = disposition.getProperty("name");pname = pname.substring(1, pname.length() - 1);String value = "";if (item.getProperty("content-type") == null) {while (mpline != null && mpline.indexOf(boundary) == -1) {mpline = in.readLine();if (mpline != null) {int d = mpline.indexOf(boundary);if (d == -1)value += mpline;elsevalue += mpline.substring(0, d - 2);}}} else {if (boundarycount > bpositions.length)sendError(socket, HTTP_INTERNALERROR, "Error processing request");int offset = stripMultipartHeaders(fbuf, bpositions[boundarycount - 2]);String path = saveTmpFile(fbuf, offset, bpositions[boundarycount - 1] - offset - 4);files.put(pname, path);value = disposition.getProperty("filename");value = value.substring(1, value.length() - 1);do {mpline = in.readLine();} while (mpline != null && mpline.indexOf(boundary) == -1);}parms.put(pname, value);}}} catch (IOException ioe) {sendError(socket, HTTP_INTERNALERROR, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());}}/*** Find the byte positions where multipart boundaries start.**/public int[] getBoundaryPositions(byte[] b, byte[] boundary) {int matchcount = 0;int matchbyte = -1;Vector matchbytes = new Vector();for (int i = 0; i < b.length; i++) {if (b[i] == boundary[matchcount]) {if (matchcount == 0)matchbyte = i;matchcount++;if (matchcount == boundary.length) {matchbytes.addElement(new Integer(matchbyte));matchcount = 0;matchbyte = -1;}} else {i -= matchcount;matchcount = 0;matchbyte = -1;}}int[] ret = new int[matchbytes.size()];for (int i = 0; i < ret.length; i++) {ret[i] = ((Integer) matchbytes.elementAt(i)).intValue();}return ret;}/*** Retrieves the content of a sent file and saves it* to a temporary file.* The full path to the saved file is returned.**/private String saveTmpFile(byte[] b, int offset, int len) {String path = "";if (len > 0) {String tmpdir = System.getProperty("java.io.tmpdir");try {File temp = File.createTempFile("NanoHTTPD", "", new File(tmpdir));OutputStream fstream = new FileOutputStream(temp);fstream.write(b, offset, len);fstream.close();path = temp.getAbsolutePath();} catch (Exception e) { // Catch exception if anySystem.err.println("Error: " + e.getMessage());}}return path;}/*** It returns the offset separating multipart file headers* from the file's data.**/private int stripMultipartHeaders(byte[] b, int offset) {int i = 0;for (i = offset; i < b.length; i++) {if (b[i] == '\r' && b[++i] == '\n' && b[++i] == '\r' && b[++i] == '\n')break;}return i + 1;}/*** Decodes the percent encoding scheme. <br/>* For example: "an+example%20string" -> "an example string"*/private String decodePercent(String str) throws InterruptedException {try {StringBuffer sb = new StringBuffer();for (int i = 0; i < str.length(); i++) {char c = str.charAt(i);switch (c) {case '+':sb.append(' ');break;case '%':sb.append((char) Integer.parseInt(str.substring(i + 1, i + 3), 16));i += 2;break;default:sb.append(c);break;}}return sb.toString();} catch (Exception e) {sendError(socket, HTTP_BADREQUEST, "BAD REQUEST: Bad percent-encoding.");return null;}}/*** Decodes parameters in percent-encoded URI-format* ( e.g. "name=Jack%20Daniels&pass=Single%20Malt" ) and* adds them to given Properties. NOTE: this doesn't support multiple* identical keys due to the simplicity of Properties -- if you need multiples,* you might want to replace the Properties with a Hashtable of Vectors or such.*/private void decodeParms(String parms, Properties p)throws InterruptedException {if (parms == null)return;StringTokenizer st = new StringTokenizer(parms, "&");while (st.hasMoreTokens()) {String e = st.nextToken();int sep = e.indexOf('=');if (sep >= 0)p.put(decodePercent(e.substring(0, sep)).trim(),decodePercent(e.substring(sep + 1)));}}/*** Returns an error message as a HTTP response and* throws InterruptedException to stop further request processing.*/private void sendError(Socket socket, String status, String msg) throws InterruptedException {sendResponse(socket, status, MIME_PLAINTEXT, null, null);throw new InterruptedException();}/*** Sends given response to the socket.*/private void sendResponse(Socket socket, String status, String mime, Properties header, StreamSource data) {try {if (status == null)throw new Error("sendResponse(): Status can't be null.");OutputStream out = socket.getOutputStream();PrintWriter pw = new PrintWriter(out);pw.print("HTTP/1.0 " + status + " \r\n");if (mime != null)pw.print("Content-Type: " + mime + "\r\n");if (header == null || header.getProperty("Date") == null)pw.print("Date: " + gmtFrmt.format(new Date()) + "\r\n");if (header != null) {Enumeration e = header.keys();while (e.hasMoreElements()) {String key = (String) e.nextElement();String value = header.getProperty(key);pw.print(key + ": " + value + "\r\n");}}pw.print("\r\n");pw.flush();if (data != null) {//long pending = data.available();	// This is to support partial sends, see serveFile()data.open();byte[] buff = new byte[8192];int read = 0;while ((read = data.read(buff)) > 0) {//if(SolidExplorer.LOG)Log.d("Explorer", "Read: "+ read +", pending: "+ data.available());out.write(buff, 0, read);}}out.flush();out.close();if (data != null)data.close();} catch (IOException ioe) {// Couldn't write? No can do.try {socket.close();} catch (Throwable t) {}}}//private Socket mySocket;}/*** URL-encodes everything between "/"-characters.* Encodes spaces as '%20' instead of '+'.*/private String encodeUri(String uri) {String newUri = "";StringTokenizer st = new StringTokenizer(uri, "/ ", true);while (st.hasMoreTokens()) {String tok = st.nextToken();if (tok.equals("/"))newUri += "/";else if (tok.equals(" "))newUri += "%20";else {newUri += URLEncoder.encode(tok);// For Java 1.4 you'll want to use this instead:// try { newUri += URLEncoder.encode( tok, "UTF-8" ); } catch ( java.io.UnsupportedEncodingException uee ) {}}}return newUri;}private int myTcpPort;private final ServerSocket myServerSocket;private Thread myThread;private File myRootDir;/*** GMT date formatter*/private static java.text.SimpleDateFormat gmtFrmt;static {gmtFrmt = new java.text.SimpleDateFormat("E, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);gmtFrmt.setTimeZone(TimeZone.getTimeZone("GMT"));}/*** The distribution licence*/private static final String LICENCE ="Copyright (C) 2001,2005-2011 by Jarno Elonen <elonen@iki.fi>\n" +"and Copyright (C) 2010 by Konstantinos Togias <info@ktogias.gr>\n" +"\n" +"Redistribution and use in source and binary forms, with or without\n" +"modification, are permitted provided that the following conditions\n" +"are met:\n" +"\n" +"Redistributions of source code must retain the above copyright notice,\n" +"this list of conditions and the following disclaimer. Redistributions in\n" +"binary form must reproduce the above copyright notice, this list of\n" +"conditions and the following disclaimer in the documentation and/or other\n" +"materials provided with the distribution. The name of the author may not\n" +"be used to endorse or promote products derived from this software without\n" +"specific prior written permission. \n" +" \n" +"THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n" +"IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n" +"OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n" +"IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n" +"INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n" +"NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n" +"DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n" +"THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n" +"(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n" +"OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.";
}
public class Streamer extends StreamServer {public static final int PORT = 7871;public static final String URL = "http://127.0.0.1:" + PORT;private SmbFile file;protected List<SmbFile> extras; //those can be subtitles// private InputStream stream;// private long length;private static Streamer instance;private static Pattern pattern = Pattern.compile("^.*\\.(?i)(mp3|wma|wav|aac|ogg|m4a|flac|mp4|avi|mpg|mpeg|3gp|3gpp|mkv|flv|rmvb)$");// private CBItem source;// private String mime;protected Streamer(int port) throws IOException {super(port, new File("."));}public static Streamer getInstance() {if (instance == null)try {instance = new Streamer(PORT);} catch (IOException e) {e.printStackTrace();}return instance;}public static boolean isStreamMedia(SmbFile file) {return pattern.matcher(file.getName()).matches();}public void setStreamSrc(SmbFile file, List<SmbFile> extraFiles) {this.file = file;this.extras = extraFiles;}@Overridepublic Response serve(String uri, String method, Properties header, Properties parms, Properties files) {Response res = null;try {SmbFile sourceFile = null;String name = getNameFromPath(uri);Log.e("youdianzishuip", "file.getName()=====" + file.getName());Log.e("youdianzishuip", "name=====" + name);if (file != null && file.getName().equals(name))sourceFile = file;else if (extras != null) {for (SmbFile i : extras) {if (i != null && i.getName().equals(name)) {sourceFile = i;break;}}}if (sourceFile == null)res = new Response(HTTP_NOTFOUND, MIME_PLAINTEXT, null);else {long startFrom = 0;long endAt = -1;String range = header.getProperty("range");if (range != null) {if (range.startsWith("bytes=")) {range = range.substring("bytes=".length());int minus = range.indexOf('-');try {if (minus > 0) {startFrom = Long.parseLong(range.substring(0, minus));endAt = Long.parseLong(range.substring(minus + 1));}} catch (NumberFormatException nfe) {}}}Log.d("Explorer", "Request: " + range + " from: " + startFrom + ", to: " + endAt);// Change return code and add Content-Range header when skipping// is requested//source.open();final StreamSource source = new StreamSource(sourceFile);long fileLen = source.length();if (range != null && startFrom > 0) {if (startFrom >= fileLen) {res = new Response(HTTP_RANGE_NOT_SATISFIABLE, MIME_PLAINTEXT, null);res.addHeader("Content-Range", "bytes 0-0/" + fileLen);} else {if (endAt < 0)endAt = fileLen - 1;long newLen = fileLen - startFrom;if (newLen < 0)newLen = 0;Log.d("Explorer", "start=" + startFrom + ", endAt=" + endAt + ", newLen=" + newLen);final long dataLen = newLen;source.moveTo(startFrom);Log.d("Explorer", "Skipped " + startFrom + " bytes");res = new Response(HTTP_PARTIALCONTENT, source.getMimeType(), source);res.addHeader("Content-length", "" + dataLen);}} else {source.reset();res = new Response(HTTP_OK, source.getMimeType(), source);res.addHeader("Content-Length", "" + fileLen);}}} catch (IOException ioe) {ioe.printStackTrace();res = new Response(HTTP_FORBIDDEN, MIME_PLAINTEXT, null);}res.addHeader("Accept-Ranges", "bytes"); // Announce that the file// server accepts partial// content requestesreturn res;}public static String getNameFromPath(String path) {if (path == null || path.length() < 2)return null;int slash = path.lastIndexOf('/');if (slash == -1)return path;elsereturn path.substring(slash + 1);}}
public class StreamSource {protected String mime;protected long fp;protected long len;protected String name;protected SmbFile file;InputStream input;protected int bufferSize;public StreamSource(SmbFile file) throws SmbException {fp = 0;len = file.length();mime = MimeTypeMap.getFileExtensionFromUrl(file.getName());name = file.getName();this.file = file;bufferSize = 1024 * 16;}/*** You may notice a strange name for the smb input stream.* I made some modifications to the original one in the jcifs library for my needs,* but streaming required returning to the original one so I renamed it to "old".* However, I needed to specify a buffer size in the constructor. It looks now like this:* <p>* public SmbFileInputStreamOld( SmbFile file, int readBuffer, int openFlags) throws SmbException, MalformedURLException, UnknownHostException {* this.file = file;* this.openFlags = SmbFile.O_RDONLY & 0xFFFF;* this.access = (openFlags >>> 16) & 0xFFFF;* if (file.type != SmbFile.TYPE_NAMED_PIPE) {* file.open( openFlags, access, SmbFile.ATTR_NORMAL, 0 );* this.openFlags &= ~(SmbFile.O_CREAT | SmbFile.O_TRUNC);* } else {* file.connect0();* }* readSize = readBuffer;* fs = file.length();* }* <p>* Setting buffer size by properties didn't work for me so I created this constructor.* In the libs folder there is a library modified by me. If you want to use a stock one, you* have to set somehow the buffer size to be equal with http server's buffer size which is 8192.** @throws IOException*/public void open() throws IOException {try {input = new SmbFileInputStream(file);if (fp > 0)input.skip(fp);} catch (Exception e) {throw new IOException(e);}}public int read(byte[] buff) throws IOException {return read(buff, 0, buff.length);}public int read(byte[] bytes, int start, int offs) throws IOException {int read = input.read(bytes, start, offs);fp += read;return read;}public long moveTo(long position) throws IOException {fp = position;return fp;}public void close() {try {input.close();} catch (IOException e) {e.printStackTrace();}}public String getMimeType() {return mime;}public long length() {return len;}public String getName() {return name;}public long available() {return len - fp;}public void reset() {fp = 0;}public SmbFile getFile() {return file;}public int getBufferSize() {return bufferSize;}}

使用代码如下 :

//开启指向本地127.0.0.1的服务器
Streamer streamer = Streamer.getInstance();
//设置路径NtlmPasswordAuthentication auth =new NtlmPasswordAuthentication(SambaManager.getDomainName(path), "lig", "123456!");
SmbFile file = new SmbFile("smb://172.16.1.73/lig/newtestsamb/jaychou.ogg", auth);
streamer.setStreamSrc(file, null);

将http的uri复制给MediaPlayer

Uri uri = Uri.parse(Streamer.URL +Uri.fromFile(new File(Uri.parse("smb://172.16.1.73/lig/newtestsamb/jaychou.ogg").getPath())).getEncodedPath());
mstarPlayer.setDataSource(context, uri);

相关文章:

播放Samba协议下的音视频文件

Samba&#xff08;也被称为SMB/CIFS&#xff09;是一个用于在局域网内共享文件和打印服务的协议&#xff0c;广泛应用于Windows和Linux系统之间的文件共享。 一、展示Samba服务器下的文件 使用如jcifs这样的Java库来在安卓应用中集成SMB/CIFS客户端功能。这个库提供了与SMB/CI…...

Excel全套213集教程

Excel全套213集教程 包含技术入门93集 图表17集 数据透视35集 公式函数68 基础入门 93节 https://www.alipan.com/s/cMxuPstkS1x 提取码: 77dd 点击链接保存&#xff0c;或者复制本段内容&#xff0c;打开「阿里云盘」APP &#xff0c;无需下载极速在线查看&#xff0c;视…...

【七 (1)指标体系建设-构建高效的故障管理指标体系】

目录 文章导航一、故障概述1、故障&#xff1a;2、故障管理&#xff1a; 二、指标体系概述1、指标2、指标体系 三、指标体系构建难点1、管理视角2、业务视角3、技术视角 四、指标体系构建原则1、与战略目标对齐2、综合和平衡3、数据可获得性4、可操作性5、具体和可衡量6、参与和…...

Go gin框架(详细版)

目录 0. 为什么会有Go 1. 环境搭建 2. 单-请求&&返回-样例 3. RESTful API 3.1 首先什么是RESTful API 3.2 Gin框架支持RESTful API的开发 4. 返回前端代码 go.main index.html 5. 添加静态文件 main.go 改动的地方 index.html 改动的地方 style.css 改动…...

Git分布式版本控制系统——Git常用命令(二)

五、Git常用命令————分支操作 同一个仓库可以有多个分支&#xff0c;各个分支相互独立&#xff0c;互不干扰 分支的相关命令&#xff0c;具体如下&#xff1a; git branch 查看分支 git branch [name] 创建分支&#x…...

LeetCode 59.螺旋矩阵II

LeetCode 59.螺旋矩阵II 1、题目 力扣题目链接&#xff1a;59. 螺旋矩阵 II - 力扣&#xff08;LeetCode&#xff09; 给你一个正整数 n &#xff0c;生成一个包含 1 到 n2 所有元素&#xff0c;且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。 示例 1&#xff1…...

03-JAVA设计模式-适配器模式

适配器模式 设么是适配器模式 它属于结构型模式&#xff0c;主要用于将一个类的接口转换成客户端所期望的另一种接口&#xff0c;从而使得原本由于接口不兼容而无法协同工作的类能够一起工作。 适配器模式主要解决的是不兼容接口的问题。在软件开发中&#xff0c;经常会有这…...

MVVM架构模式

目录 MVVM 数据绑定方式 实现方式 Model View ViewModel 数据绑定方式 vue&#xff1a;&#xff1a; 数据劫持和发布-订阅模式&#xff1a; Object.defineProperty() 方法来劫持&#xff08;监控&#xff09;各属性的 getter 、setter &#xff0c;并在数据&#xff08;对…...

leetcode2924--找到冠军II

1. 题意 给定一个有向无环图&#xff0c;方向表示胜负关系&#xff1b;求最后胜出的人。 2. 题解 将所有人标记为胜者&#xff0c;统计出度去掉对应胜者标记&#xff1b; 最后统计胜者数目&#xff0c;是否大于1&#xff0c;若大于1&#xff0c;则没有胜者&#xff0c;否则…...

嵌入式|蓝桥杯STM32G431(HAL库开发)——CT117E学习笔记13:RTC实时时钟

系列文章目录 嵌入式|蓝桥杯STM32G431&#xff08;HAL库开发&#xff09;——CT117E学习笔记01&#xff1a;赛事介绍与硬件平台 嵌入式|蓝桥杯STM32G431&#xff08;HAL库开发&#xff09;——CT117E学习笔记02&#xff1a;开发环境安装 嵌入式|蓝桥杯STM32G431&#xff08;…...

统一用安卓Studio修改项目包名

可以逃跑&#xff0c;可以哭泣&#xff0c;但不可以放弃 --《鬼灭之刃》 修改项目包名 1&#xff09;选中项目中药修改的包名&#xff1a; 2)目结构显示方式&#xff0c;取消 Compact Middle Packages 选项&#xff1b; 3)右键要修改的包名&#xff0c;选择 Refactor —— Re…...

Spring Cloud Gateway详细介绍以及实现动态路由

一. 简介 Spring Cloud Gateway This project provides a libraries for building an API Gateway on top of Spring WebFlux or Spring WebMVC. Spring Cloud Gateway aims to provide a simple, yet effective way to route to APIs and provide cross cutting concerns to …...

transformer上手(6)—— 微调预训练模型

1 加载数据集 以同义句判断任务为例&#xff08;每次输入两个句子&#xff0c;判断它们是否为同义句&#xff09;&#xff0c;构建我们的第一个 Transformers 模型。我们选择蚂蚁金融语义相似度数据集 AFQMC 作为语料&#xff0c;它提供了官方的数据划分&#xff0c;训练集 / …...

web前端框架设计第四课-条件判断与列表渲染

web前端框架设计第四课-条件判断与列表渲染 一.预习笔记 1.条件判断 1-1&#xff1a;v-if指令&#xff1a;根据表达式的值来判断是否输出DOM元素 1-2&#xff1a;template中使用v-if 1-3&#xff1a;v-else 1-4&#xff1a;v-else-if 1-5&#xff1a;v-show&#xff08;不支…...

计算机网络:数据链路层 - CSMA/CD协议

计算机网络&#xff1a;数据链路层 - CSMA/CD协议 媒体接入控制CSMA/CD协议截断二进制指数退避算法帧长与帧间间隔信道利用率 媒体接入控制 如图所示&#xff0c;这是一根同轴电缆&#xff0c;有多台主机连接到这根同轴电缆上&#xff0c;他们共享这根传输媒体&#xff0c;形成…...

力扣LeetCode138. 复制带随机指针的链表 两种解法(C语言实现)

目录 题目链接 题目分析 题目定位&#xff1a; 解题思路 解题思路1&#xff08;粗暴但是复杂度高&#xff09; 解题思路2&#xff08;巧妙并且复杂度低&#xff09; 题目链接 138. 复制带随机指针的链表https://leetcode-cn.com/problems/copy-list-with-random-pointer/ …...

强大的压缩和解压缩工具 Keka for Mac

Keka for Mac是一款功能强大的压缩和解压缩工具&#xff0c;专为Mac用户设计。它支持多种压缩格式&#xff0c;包括7z、Zip、Tar、Gzip和Bzip2等&#xff0c;无论是发送电子邮件、备份文件还是节省磁盘空间&#xff0c;Keka都能轻松满足用户需求。 这款软件的操作简单直观&…...

论文速读:Do Generated Data Always Help Contrastive Learning?

在对比学习领域&#xff0c;最近很多研究利用高质量生成模型来提升对比学习 给定一个未标记的数据集&#xff0c;在其上训练一个生成模型来生成大量的合成样本&#xff0c;然后在真实数据和生成数据的组合上执行对比学习这种使用生成数据的最简单方式被称为“数据膨胀”这与数据…...

华为欧拉系统(openEuler-22.03)安装深信服EasyConnect软件(图文详解)

欧拉镜像下载安装 iso镜像官网下载地址 选择最小化安装&#xff0c;标准模式 换华为镜像源 更换华为镜像站&#xff0c;加速下载&#xff1a; sed -i "s#http://repo.openeuler.org#https://mirrors.huaweicloud.com/openeuler#g" /etc/yum.repos.d/openEuler.r…...

git commit --amend用法

一、git commit --amend 修改提交信息&#xff1a;您可以使用 git commit --amend 命令来修改最新提交的提交信息。执行该命令后&#xff0c;Git 将会打开文本编辑器&#xff08;通常是的默认文本编辑器&#xff09;&#xff0c;以便编辑提交信息。完成编辑后保存并关闭编辑器…...

智慧工地云平台源码,基于微服务架构+Java+Spring Cloud +UniApp +MySql

智慧工地管理云平台系统&#xff0c;智慧工地全套源码&#xff0c;java版智慧工地源码&#xff0c;支持PC端、大屏端、移动端。 智慧工地聚焦建筑行业的市场需求&#xff0c;提供“平台网络终端”的整体解决方案&#xff0c;提供劳务管理、视频管理、智能监测、绿色施工、安全管…...

Vue3 + Element Plus + TypeScript中el-transfer穿梭框组件使用详解及示例

使用详解 Element Plus 的 el-transfer 组件是一个强大的穿梭框组件&#xff0c;常用于在两个集合之间进行数据转移&#xff0c;如权限分配、数据选择等场景。下面我将详细介绍其用法并提供一个完整示例。 核心特性与用法 基本属性 v-model&#xff1a;绑定右侧列表的值&…...

【位运算】消失的两个数字(hard)

消失的两个数字&#xff08;hard&#xff09; 题⽬描述&#xff1a;解法&#xff08;位运算&#xff09;&#xff1a;Java 算法代码&#xff1a;更简便代码 题⽬链接&#xff1a;⾯试题 17.19. 消失的两个数字 题⽬描述&#xff1a; 给定⼀个数组&#xff0c;包含从 1 到 N 所有…...

鸿蒙中用HarmonyOS SDK应用服务 HarmonyOS5开发一个生活电费的缴纳和查询小程序

一、项目初始化与配置 1. 创建项目 ohpm init harmony/utility-payment-app 2. 配置权限 // module.json5 {"requestPermissions": [{"name": "ohos.permission.INTERNET"},{"name": "ohos.permission.GET_NETWORK_INFO"…...

图表类系列各种样式PPT模版分享

图标图表系列PPT模版&#xff0c;柱状图PPT模版&#xff0c;线状图PPT模版&#xff0c;折线图PPT模版&#xff0c;饼状图PPT模版&#xff0c;雷达图PPT模版&#xff0c;树状图PPT模版 图表类系列各种样式PPT模版分享&#xff1a;图表系列PPT模板https://pan.quark.cn/s/20d40aa…...

是否存在路径(FIFOBB算法)

题目描述 一个具有 n 个顶点e条边的无向图&#xff0c;该图顶点的编号依次为0到n-1且不存在顶点与自身相连的边。请使用FIFOBB算法编写程序&#xff0c;确定是否存在从顶点 source到顶点 destination的路径。 输入 第一行两个整数&#xff0c;分别表示n 和 e 的值&#xff08;1…...

浪潮交换机配置track检测实现高速公路收费网络主备切换NQA

浪潮交换机track配置 项目背景高速网络拓扑网络情况分析通信线路收费网络路由 收费汇聚交换机相应配置收费汇聚track配置 项目背景 在实施省内一条高速公路时遇到的需求&#xff0c;本次涉及的主要是收费汇聚交换机的配置&#xff0c;浪潮网络设备在高速项目很少&#xff0c;通…...

【Nginx】使用 Nginx+Lua 实现基于 IP 的访问频率限制

使用 NginxLua 实现基于 IP 的访问频率限制 在高并发场景下&#xff0c;限制某个 IP 的访问频率是非常重要的&#xff0c;可以有效防止恶意攻击或错误配置导致的服务宕机。以下是一个详细的实现方案&#xff0c;使用 Nginx 和 Lua 脚本结合 Redis 来实现基于 IP 的访问频率限制…...

Spring AI Chat Memory 实战指南:Local 与 JDBC 存储集成

一个面向 Java 开发者的 Sring-Ai 示例工程项目&#xff0c;该项目是一个 Spring AI 快速入门的样例工程项目&#xff0c;旨在通过一些小的案例展示 Spring AI 框架的核心功能和使用方法。 项目采用模块化设计&#xff0c;每个模块都专注于特定的功能领域&#xff0c;便于学习和…...

热门Chrome扩展程序存在明文传输风险,用户隐私安全受威胁

赛门铁克威胁猎手团队最新报告披露&#xff0c;数款拥有数百万活跃用户的Chrome扩展程序正在通过未加密的HTTP连接静默泄露用户敏感数据&#xff0c;严重威胁用户隐私安全。 知名扩展程序存在明文传输风险 尽管宣称提供安全浏览、数据分析或便捷界面等功能&#xff0c;但SEMR…...