【问题标题】:How to Convert audio .mp3 file to String and vice versa?如何将音频 .mp3 文件转换为字符串,反之亦然?
【发布时间】:2016-01-25 11:51:32
【问题描述】:

是否可以将音频mp3文件转换为字符串数据用于向服务器发送数据, 服务器会将字符串数据返回给我的应用程序,我想将该数据转换为 mp3 文件并播放音频。

我正在使用此代码将 mp3 文件转换为字符串数据

public static String readFileAsString(String filePath) throws java.io.IOException {

    BufferedReader reader = new BufferedReader(new FileReader(filePath));
    String line, results = "";
    while( ( line = reader.readLine() ) != null)
    {
        results += line;
    }
    reader.close();
    return results;

}

我不知道如何从转换后的字符串数据中取回我的 mp3 文件。

如果可能,那怎么办?谁来帮帮我。

或任何其他满足此要求的解决方案告诉我:我想将音频和视频文件传递到服务器并从服务器返回以在应用程序中使用。

【问题讨论】:

  • 您不应将二进制文件作为字符串传输。
  • 那么将mp3文件传递到服务器并从服务器返回的解决方案是什么。
  • 不知道字符串转换的原因。但是,只是问一下,为什么不上传带有数据库轨道的文件本身并通过流式传输返回?
  • @vini 如果还有其他可能性,请提供链接,我会尝试这样做。

标签: android audio-streaming


【解决方案1】:

使用 Base64.encodeToString() 试试这个http://developer.android.com/reference/android/util/Base64.html#encodeToString%28byte%5B%5D,%20int%29

File file = new File(Environment.getExternalStorageDirectory() + "/hello-4.wav");
byte[] bytes = FileUtils.readFileToByteArray(file);

String encoded = Base64.encodeToString(bytes, 0);                                       
Utilities.log("~~~~~~~~ Encoded: ", encoded);

byte[] decoded = Base64.decode(encoded, 0);
Utilities.log("~~~~~~~~ Decoded: ", Arrays.toString(decoded));

try
{
    File file2 = new File(Environment.getExternalStorageDirectory() + "/hello-5.wav");
    FileOutputStream os = new FileOutputStream(file2, true);
    os.write(decoded);
    os.close();
}
catch (Exception e)
{
    e.printStackTrace();
}



public class FileUtils {

    /**
     * Instances should NOT be constructed in standard programming.
     */
    public FileUtils() { }

    /**
     * The number of bytes in a kilobyte.
     */
    public static final long ONE_KB = 1024;

    /**
     * The number of bytes in a megabyte.
     */
    public static final long ONE_MB = ONE_KB * ONE_KB;

    /**
     * The number of bytes in a gigabyte.
     */
    public static final long ONE_GB = ONE_KB * ONE_MB;



    public static String readFileToString(
            File file, String encoding) throws IOException {
        InputStream in = new java.io.FileInputStream(file);
        try {
            return IOUtils.toString(in, encoding);
        } finally {
            IOUtils.closeQuietly(in);
        }
    }



    }

}

【讨论】:

  • 我必须用这个转换什么
  • 我再次编辑了代码只是再次检查一下我的代码中有合并 fileutil 类
【解决方案2】:
Error:(49, 41) error: cannot find symbol method readFileToByteArray(File)

我认为您没有在 FileUtils 中定义该方法,是吗?

我已经通过如下修改代码解决了这个问题:

//byte[] bytes = FileUtils.readFileToByteArray(file);
            byte[] bytes = new byte[(int)file.length()];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-05
    • 2010-09-12
    • 1970-01-01
    • 2011-05-27
    • 1970-01-01
    • 2017-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多