A Times Square bloodbath was narrowly avoided because the machine-pistol-toting thug who fired at a cop flipped the gun on its side like a character out of a rap video, causing the weapon to jam after two shots, law-enforcement sources said yesterday.

When scam artist Raymond “Ready” Martinez held the MAC-10-style gun parallel to the ground, it caused the ejecting shells to “stovepipe,” or get caught vertically in the chamber, the sources said. The gun is designed to be fired only in a vertical position.

If he had fired the weapon — which had another 27 rounds in the clip — properly, Martinez, 25, could have killed the hero cop pursuing him and countless others walking through the swarming tourist mecca Thursday morning.

Instead, Sgt. Christopher Newsom was able to return fire — killing Martinez with four shots before anyone was hurt.

The fatal gun battle erupted after Martinez bolted from cops who approached him for aggressively peddling his own rap CDs to tourists and shaking them down for cash. Newsom gave chase and shouted for Martinez to put up his hands.

Martinez instead pulled the machine gun from a sling under his coat and turned to fire as he ran into the parking breezeway within the Marriott Marquis Hotel.

One of the shots shattered a gift-shop window and a second struck the car of an out-of-town couple coming to see the Rockettes at Radio City Music Hall.

In rap songs on his Web page, Martinez boasted of taking aim at a police sergeant.

“If they call the cops, then I’m aiming at the sergeant, like aiming at my target,” said Martinez, who raps under the name “Ready.”

“And sure that f- – -ing dirty pig will feel it the hardest.”

But the boast was empty as Newsom’s better training bested Martinez’s drummed-up bravado. In the end, Martinez unwittingly rapped about his own fate.

“Tell forensics to bring the chalk,” he said, describing the outline that detectives draw around a body on the street.

Investigators are still trying to figure out where Martinez — who had a warrant for failing to show in court on charges he beat his wife — got the high-powered Masterpiece Arms-built weapon.

The gun had been stolen from its owner, a woman named Jordan Kelsey-Stewart, 25, who bought it from Dale’s Guns in Powhatan, Va., on Oct. 18, sources said.

It was stolen from Kelsey-Stewart’s car on Oct. 28 in Richmond, Va. What happened next is unclear, but the feds want to talk to her to see if she had any connection to the shooter.

A business card of the gun shop was found on Martinez.

Meanwhile, cops found another gun at his house last night, a .22-caliber revolver.

murray.weiss@nypost.com

