Why do I need transistor in the following mains power failure circuit?
Yes, the diode does work as a switch.  But without the transistor, only a very small current can flow through the buzzer.







simulate this circuit &ndash; Schematic created using CircuitLab

When the mains power is on, D2 is reverse biased. But when the mains go out, D2 becomes forward biased.  The buzzer is then connected to a 8.3 V voltage source with 1 kOhm resistance, that resistance will limit the current and it could drop too much voltage for the buzzer to function.

You could simply reduce the value of R1, but the power dissipation will be high: a 130 Ohm 1W resistor is the lowest you could use.

So lets use something to amplify a small current through the dummy load into a big current through the buzzer:



It looks like a 3V battery?

When the main goes out D1 becomes forward biased and the voltage across R1 becomes Vbat - Vbe - Vd1 = 1.7 volts.  Only 1.7 mA flows through R1 and gets split between R2 and the base emitter junction of T1.  R2 conducts 0.7V/2.2kOhm = 0.3mA of the current, leaving the remaining 1.4 mA to the transistor.

A typical general purpose transistor has a current amplification of at least 100 meaning that it can supply at least up to 140 mA of current to the buzzer.  And the voltage won't drop too low if the transistor is saturated.