解決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上面的解決方案。主要是下面幾點:
- 使用文字水印時需要指定一個自定義的字體文件
- 字體文件需要一個絕對路徑
- Android中不能使用項目中app/ 下的路徑
- 要把自定義字體文件放在res/fonts目錄下(在AS 4.1.1中要新建文件夾),然后在程序執(zhí)行時保存到內部存儲目錄-/data/user
下面是具體的步驟:
- 我使用的字體是Arial.ttf 可以百度自行下載
- 新建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 - 在程序運行時把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) {// 循環(huán)從輸入流讀取buffer字節(jié)
// 將Buffer中的數據寫到outputStream對象中
fos.write(buffer, 0, lenght);
}
fos.flush();// 刷新緩沖區(qū)
// 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的最終效果

最終效果