Macbeth had planned to pretend to have been sound asleep when Duncan's body was found, but the prolonged knocking at the gate finally forced him to make an appearance. The drunken porter serves to explain why Macduff had to knock so long for admission. The porter explains that all the servants, and presumably the guards, were drunk. Shakespeare made this scene funny to get the audience laughing, so that they would overlook the incongruity of the whole castle staff being drunk when the king and important nobles were guests. Shakespeare thought it essential to have Macduff and Macbeth present together when Macduff finds that Duncan has been murdered in his bed. Macbeth is forced to suffer through the scene he was hoping to avoid by playing possum. Macduff rings an alarm bell and arouses everybody. Macbeth has to put on an act of surprise, dismay, and innocence, when in actuality he feels overwhelmed with guilt and shame. He says to himself:
Had I but died an hour before this chance,
I had lived a blessed time; for from this instant
There's nothing serious in mortality.
It is only because of the prolonged knocking that the porter is brought onstage to make his drunken speech. No doubt Shakespeare had an actor in his company who was good at playing such clownish scenes, and he was probably a favorite with Shakespeare's audiences.