Android Ffmpeg Cannot find a valid font for the family Sans

解决Android Ffmpeg Cannot find a valid font for the family Sans 问题

在Android中使用FFmpeg添加文字水印时出现下面的错误提示:

[Parsed_drawtext_0 @ 0x70fc22fe00] Cannot find a valid font for the family Sans
[AVFilterGraph @ 0x71031fc980] Error initializing filter 'drawtext'

查看了很多文章,里面都是说要指定fontfill,这个是没有问题的,但是其他文章的例子都是windows上面使用ffmpeg的(FFmpeg相关的文章确实不多,也说明了音视频相关的技术依然并不普及,是非常有门槛的)。
最后通过我自己的理解+猜测,再参考其他文章的思路,终于找到了Android上面的解决方案。主要是下面几点:

  1. 使用文字水印时需要指定一个自定义的字体文件
  2. 字体文件需要一个绝对路径
  3. Android中不能使用项目中app/ 下的路径
  4. 要把自定义字体文件放在res/fonts目录下(在AS 4.1.1中要新建文件夹),然后在程序执行时保存到内部存储目录-/data/user

下面是具体的步骤:

  1. 我使用的字体是Arial.ttf 可以百度自行下载
  2. 新建res/fonts目录,并把字体文件复制进去,注意:字体文件名要改成全小写 也就是arial.ttf,不然Android Studio会编译报错'A' is not a valid file-based resource name character: File-based resource names must contain only lowercase a-z, 0-9, or underscore
  3. 在程序运行时把arial.ttf写入到内部存储中
protected void onCreate(Bundle savedInstanceState) {
...
doSaveTTF();
...
}
private void doSaveTTF() {
        File filesDir = MainActivity.this.getFilesDir();
        File puhuitiMiniPath = new File(filesDir, "arial.ttf");
        //判断该文件存不存在
        if (!puhuitiMiniPath.exists()) {
            //如果不存在,开始写入文件
            copyFilesFromRaw(R.font.arial, "arial.ttf", MainActivity.this.getFilesDir().getAbsolutePath());
        }
    }
void copyFilesFromRaw(int id, String fileName, String storagePath){
        InputStream inputStream = MainActivity.this.getResources().openRawResource(id);
        storagePath = storagePath + File.separator + fileName;

        File file = new File(storagePath);
        try {
            if (!file.exists()) {
                // 1.建立通道对象
                FileOutputStream fos = new FileOutputStream(file);
                // 2.定义存储空间
                byte[] buffer = new byte[inputStream.available()];
                // 3.开始读文件
                int lenght = 0;
                while ((lenght = inputStream.read(buffer)) != -1) {// 循环从输入流读取buffer字节
                    // 将Buffer中的数据写到outputStream对象中
                    fos.write(buffer, 0, lenght);
                }
                fos.flush();// 刷新缓冲区
                // 4.关闭流
                fos.close();
                inputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

之后在FFmpeg加文字水印的命令中使用自定义字体的绝对路径就可以成功了

String drawtext = "Ffmpeg -I xxx.mp4 drawtext=text='AAAAAA':fontfile='/data/user/0/com.sza.shorvideoassistant/files/arial.ttf':fontcolor=#ffffff:fontsize=33 -y xxx.mp4;

我做的demo的最终效果


最终效果

你可能感兴趣的:(Android Ffmpeg Cannot find a valid font for the family Sans)