播放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);

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/810115.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

QT:QMainWindow、ui界面、资源文件的添加、信号和槽

1.练习&#xff1a;使用手动连接&#xff0c;将登录框中的取消按钮使用qt4版本的连接到自定义的槽函数中&#xff0c;在自定义的槽函数中调用关闭函数 #include "widget.h" #include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(…

设计模式-开闭原则和迪米特法则

开闭原则 基本介绍 开闭原则(Open Closed Principle) 是编程中最基础、最重要的设计原则一个软件实体如类&#xff0c;模块和函数应该对扩展开放(对提供方)&#xff0c;对修改关闭(对使用方)。用抽象构建框架&#xff0c;用实现扩展细节。当软件需要变化时&#xff0c;尽量通…

第6章 6.3.1 正则表达式的语法(MATLAB入门课程)

讲解视频&#xff1a;可以在bilibili搜索《MATLAB教程新手入门篇——数学建模清风主讲》。​ MATLAB教程新手入门篇&#xff08;数学建模清风主讲&#xff0c;适合零基础同学观看&#xff09;_哔哩哔哩_bilibili 正则表达式可以由一般的字符、转义字符、元字符、限定符等元素组…

算法题解记录8+++爬楼梯(百日筑基)

题目描述&#xff1a; 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢&#xff1f; 示例 1&#xff1a; 输入&#xff1a;n 2 输出&#xff1a;2 解释&#xff1a;有两种方法可以爬到楼顶。 1. 1 阶…

KVM虚拟机

文章目录 QEMU-KVM介绍虚拟网卡流程网卡透访流程 QEMU-KVM介绍 QEMU ● QEMU是一个主机上的VMM (Virtual machine monitor), 通过动态二进制模拟CPU&#xff0c;并提供一系列的硬件模型&#xff0c;使Guest OS能够与Host硬件交互。 ● QEMU的代码中有完整的虚拟机实现&#xf…

【C++】1.从C语言转向C++

目录 一.对C的认识 二.C的关键字 三.命名空间 3.1命名空间的定义 3.2命名空间的使用 四.C的输入与输出 五.缺省参数 5.1全缺省参数 5.2半缺省参数 六.函数重载 七.引用 7.1引用的特性 7.2引用和指针的区别 八.内联函数 九.auto关键字&#xff08;C1…

WEB漏洞——XXE

文章目录 前言一、XXE简述及XML基础XXE简述XML基础xml简介文档格式xml树结构xml其它xml语法1、格式良好的xml2、编写第一段XML代码DTD介绍内部文档声明(即DTD在XML源文件中)外部文档声明(DTD位于XML源文件的外部)XML文档构建模块Elements(元素)数量词的用法Attributes(属…

常州南京旅游安排

第一天&#xff1a;中华恐龙园初体验与市区美食 上午&#xff08;10:30 - 12:00&#xff09; 早晨提前出发&#xff0c;争取早点进入&#xff0c;以减少热门项目的排队时间。10:00 到达园区后&#xff0c;首先前往“4D过山车”等热门项目&#xff0c;这些项目通常人气较高&am…

CISA :恶意软件分析平台Malware Next-Gen全新升级

本周三&#xff0c;美国网络安全和基础设施安全局&#xff08;CISA&#xff09;发布了新版恶意软件分析平台Malware Next-Gen&#xff0c;现在公众可以提交任意恶意软件样本供 CISA 分析。 据悉&#xff0c;Malware Next-Gen 可用于检查恶意软件样本中是否存在可疑项目。它最初…

数据生成 | Matlab实现基于SNN浅层神经网络的数据生成

数据生成 | Matlab实现基于SNN浅层神经网络的数据生成 目录 数据生成 | Matlab实现基于SNN浅层神经网络的数据生成生成效果基本描述模型描述程序设计参考资料 生成效果 基本描述 1.Matlab实现基于SNN浅层神经网络的数据生成&#xff0c;运行环境Matlab2021b及以上&#xff1b; …

在windows中anaconda中安装fasttext (whl 文件安装)

Anaconda安装第三方包&#xff08;whl文件&#xff09; windows 安装fasttext 一直不成功&#xff0c;python 版本3.8 网上教程都是 https://www.lfd.uci.edu/~gohlke/pythonlibs/#fasttext 下载然后安装&#xff0c;但是这个网站里我没找到哈哈哈。。。 然后就是成功方案&am…

Pygame教程10:在背景图片上,添加一个雪花特效

------------★Pygame系列教程★------------ Pygame经典游戏&#xff1a;贪吃蛇 Pygame教程01&#xff1a;初识pygame游戏模块 Pygame教程02&#xff1a;图片的加载缩放旋转显示操作 Pygame教程03&#xff1a;文本显示字体加载transform方法 Pygame教程04&#xff1a;dra…

移植 amd blas 到 cuda 生态

1&#xff0c;下载源码 GitHub - ROCm/rocBLAS: Next generation BLAS implementation for ROCm platform $ git clone --recursive https://github.com/ROCm/rocBLAS.git 2&#xff0c; 编译 2.1 不带Tensile的编译 如果是在conda环境中&#xff0c;需要deactive conda 环境…

信息学奥赛一本通T1457-Power Strings【KMP】

信息学奥赛一本通T1457-Power Strings - C语言网 (dotcpp.com) #include <iostream> #include <algorithm> #include <cstring> using namespace std; const int N1e6100; char str[N]; int nex[N]; int res0; signed main() {while(scanf("%s",st…

[2024]最新激活Navicat教程附激活码

PS&#xff1a;在开始前&#xff0c;建议先断开本地网络&#xff01;&#xff01;&#xff01;建议先断开本地网络&#xff01;&#xff01;&#xff01;建议先断开本地网络&#xff01;&#xff01;&#xff01; 1 安装 1.1 点击下一步 1.2 许可证选择“我同意”&#xff0c…

【云计算】云网络产品体系概述

云网络产品体系概述 在介绍云网络产品体系前&#xff0c;先介绍几个与云计算相关的基础概念。 阿里云在基础设施层面分为 地域 和 可用区 两层&#xff0c;关系如下图所示。在一个地域内有多个可用区&#xff0c;每个地域完全独立&#xff0c;每个可用区完全隔离&#xff0c;同…

ViT:拉开Trasnformer在图像领域正式挑战CNN的序幕 | ICLR 2021

论文直接将纯Trasnformer应用于图像识别&#xff0c;是Trasnformer在图像领域正式挑战CNN的开山之作。这种简单的可扩展结构在与大型数据集的预训练相结合时&#xff0c;效果出奇的好。在许多图像分类数据集上都符合或超过了SOTA&#xff0c;同时预训练的成本也相对较低   来源…

安装 Kali NetHunter (完整版、精简版、非root版)、实战指南、ARM设备武器化指南

From&#xff1a;https://www.kali.org/docs/nethunter/ NetHunter 实战指南&#xff1a;https://www.vuln.cn/6430 乌云 存档&#xff1a;https://www.vuln.cn/wooyundrops 1、Kali NetHunter Kali NetHunter 简介 Net&#xff08;网络&#xff09;&#xff0c;hunter&#x…

今天讲讲MYSQL数据库事务怎么实现的!

目录 什么是数据库事务 Mysql如何保证原子性 Mysql如何保证持久性 MySQL怎么保证隔离性 事务隔离级别 脏读的解决 不可重复读的解决 幻读的解决 MVCC实现 Read View 那么RC、RR级别下的InnoDB快照读有什么不同&#xff1f; 什么是数据库事务 数据库事务是指一组数据…

各个微前端框架的优劣浅谈

各个微前端框架都有其独特的优势和劣势&#xff0c;下面我将针对几个主流的微前端框架进行简要的优劣分析&#xff1a; single-spa 优势&#xff1a; 轻量级&#xff1a;single-spa是一个非常轻量级的微前端框架&#xff0c;它主要提供了一个加载和管理微应用的机制&#xff0c…