I had a similar problem twice in the past, once with an ordinary 21 speed bike and once with an eight speed ebike (even with power turned off). In both cases it sounded as if the hub was been hit with a small hammer (a deep tapping sound). In both cases, it was noticeable that there was play in the freewheel bearing and in both cases, I dismantled the freewheel and removed one of the packing (shim) washers, instead of replacing freewheel. Anyhow, in your case, I would (with the bike turned off) check the freewheel by grabbing gear cluster and see if there is much side to side rocking/play. Even the smallest amount can cause the freewheel body to knock against the hub side at its bearing.