The courthouse at the corner of Scheelegatan and Fleminggatan is hardly what you'd call a marvel of modern Swedish design. Red-brick, nondescript, it's also the last place in Stockholm you'd go looking for a party. But if you had been there a fortnight ago, that's exactly what you'd have found.

For the last two weeks of February, room nine of the city's district court played host to the trial of The Pirate Bay, a Swedish website that compiles links to BitTorrent files – a particularly efficient form of file-sharing – from across the internet. As the world's largest BitTorrent "tracker" site (and the 108th most popular site on the web), The Pirate Bay boasts almost 3.5 million registered users, a further 21.5 million unregistered users, and a billion page views per month. But many of the files the six-year-old site tracks and indexes are illicit versions of copyrighted material, and the film and music industries brought the site to court in the hope of making it an example to pirates everywhere.

However, proceedings did not go quite to plan. Instead of coming quietly, the three mischievous young men who run The Pirate Bay turned their trial into a sell-out show. Their friends from the anti-copyright think-tank Piratbyran ("The Pirate Bureau") turned up every day in a brightly painted campaign bus. Student bands played for supporters outside the court and, at the end of the trial's first week, the defendants threw a party at a nightclub in central Stockholm, offering free champagne to every guest.

Download the new Independent Premium app Sharing the full story, not just the headlines

So confident are the trio that they set up another website to cover the trial independently of the mainstream media. They named it Spectrial, a combination of "trial" and "spectacle". Tickets for half a day in the courtroom changed hands for €60 (£55) each on the black market, more than most rock concerts. The trial concluded last week, and both sides now await the verdict of the judging panel, due in April. But, to their fellow file-sharers, Gottfrid Svartholm Warg, Peter Sunde Kolmisoppi and Fredrik Neij are already folk heroes.

***

Meanwhile, on the other side of Stockholm, a new internet company has turned this demand for free media into a viable business model that the music industry seems willing to stomach. Spotify, launched in October last year, is a piece of music software that looks not unlike iTunes, yet allows you to listen to a vast, growing catalogue of streamed tracks for free – as long as you are prepared to endure around a minute of advertising per hour. A premium version, costing £9.99 per month, suppresses the ads and offers exclusive content. Listeners can exchange their favourite playlists with one another online.

This internet jukebox's global user numbers reached a million this week and are increasing by 20,000 a day, while its catalogue of tracks grows at a similar rate. At least 250,000 Spotify users are in the UK, where the service recently became freely available for download. And, in February, it executed its first big industry coup, giving users the chance to hear U2's new album a week before its physical release.

Spotify has harnessed a voracious appetite for sharing free culture online to create a legitimate alternative to online piracy. But it's a model that would never have been embraced by the entertainment industry without the likes of The Pirate Bay forcing labels and studios to confront the future. Both sites are part of an ever-fertile technology community in Sweden's melting pot of expertise, experience and innovation; Stockholm is, in attitude and actuality, the capital of a new virtual world.

Spotify's Stockholm HQ is just what you'd expect of a flourishing internet start-up. In one corner of the open-plan office is a heap of bean-bags. There's a pool table, a foosball table and an air hockey table. Hip, youthful employees drink coffee from a Nespresso machine; developers brainstorm in an alcove where the bright wooden floor gives way to faux grass and pot plants, which match the bright green styling of the Spotify logo in the lobby. Already the Spotify staff – whose numbers have ballooned from 15 to about 70 – are looking for bigger premises.

Daniel Ek, a cerebral-seeming 25-year-old in a designer sweater, is Spotify's founder. A serial CEO, he started his first company in 1997 at the age of 14. His last venture was Stardoll, a social network for young girls that now has 26 million members worldwide. He was once CEO of uTorrent, the developers of a popular – and legal – BitTorrent file-sharing platform that doubtless accounts for a lot of The Pirate Bay's traffic (uTorrent was created by Ludvig Strideus, currently a Spotify employee). Ek estimates that one-third of Stockholm's inhabitants now use Spotify regularly. "I've created things that millions of people have used before," he says, "but this is the first time people have started to recognise me in the street."

Tech companies litter Stockholm's centre, and Ek is the latest in a line of stellar Swedish web entrepreneurs. There's Martin Lorentzon, Spotify's co-founder and creator of the marketing site TradeDoubler. There's Peter Alvarsson, who in 2006 set up Headweb, a legal film-download site that puts BitTorrent technology to legitimate use. In 2001, Niklas Zennstrom founded Kazaa, a peer-to-peer file-sharing network that frequently faced lawsuits from the record industry. He went on to establish Skype, the internet telephone service, and Joost, a legal peer-to-peer video distribution platform. Way back in 1995, Jonas Svensson set up Spray, a web-page design site that became the biggest such service in the world.

Perhaps the most important was Jonas Birgersson, who made millions when he floated his internet consultancy Framfab in 1999. Birgersson, then 29, used his fortune to establish a broadband service, Bredbandsbolaget, which by 2001 had delivered high-speed broadband to half a million Swedish homes. At the same time, a government drive was under way to get not only the internet, but also a tax-free desktop computer, into every household. Sweden's population of nine million soon became the most wired in the world.

"Bredbandsbolaget connected a lot of Swedes," Ek says. "In 1997, I was one of the top 1 per cent of people in Europe, with broadband access of 10Mb in both directions [upload and download]. That was over a decade ago, and most of the UK still doesn't have that sort of access."

Rick Falkvinge is the leader of Sweden's most plugged-in political group, The Pirate Party. "In the rest of Europe," he says, "the internet roll-out was done by telecommunications companies, who had an incentive to delay it for as long as possible because it shattered their existing business model. When you put disruptive technology into everyone's hands, it changes public perceptions of what you can, and should, do with it."

It didn't take the internet to give the Swedes an international outlook. Thanks to linguistic isolation and high-quality free education, almost everyone in Stockholm speaks flawless English. The state prizes its science and engineering teaching, and the country has always punched above its weight as an exporter, with telecoms brands like Ericsson, but also with Volvo, Saab, Tetrapak, Ikea and H&M. Free music schools are often cited as the cause of Sweden's chart success; the country is the third-largest exporter of pop music after the US and the UK.

Sweden was exporting free media before the tech revolution. The free newspaper Metro was established in Stockholm in 1995 before spreading to more than 100 cities worldwide. Swedes are voracious consumers of news, and every small town still has a local rag. But, says the Metro CEO Andreas Ohlson: "Younger audiences prefer our free papers to paid subscription ones. Our typical reader is 27 years old, urban, active and likes to travel. They're the same people who use Spotify and The Pirate Bay."

Sweden has felt the effects of the recession as strongly as anywhere – Saab is on the brink of bankruptcy – but that didn't stop two Scandinavian investment companies pumping €15m into Spotify last year. Ek and Lorentzen had already invested £7m. Ek is convinced that the collapse in ad revenues will not affect his company's growth, as he can offer advertisers a powerful form of targeted advertising. "Unlike old radio advertising, which has to rely on listener surveys, we can tell brands that we are reaching, say, 35,000 males in London between the ages of 25 and 35, and right now they're listening to cheerful music. If you're a brand that wants to be upbeat, you can associate yourself with that audience. We want to facilitate brand partnerships with record companies and individual artists, too."

Spotify has been negotiating with the record labels since the site was conceived in autumn 2006, but now that a buzz has built up, new music partners are coming on board every day. In early February, independent distributor CD Baby signed up, with the promise of almost a million new tracks. With U2 in the tank, Ek believes he can attract the few big acts still holding out, such as Metallica, AC/DC and Prince. "The other day Johnny Greenwood [of Radiohead] posted a Spotify playlist on his blog, so hopefully we can have a discussion with Radiohead about getting their catalogue."

And it's not just stadium bands. "Spotify could be a tool for breaking new artists," Ek says. "Glasvegas are big in the UK but no one thought about getting them to Scandinavia. We had them on Spotify, the radio picked it up, their label took them to iTunes, and now their Stockholm shows sell out in 30 minutes. Their LP wasn't even supposed to be released here."

This was no top-down marketing drive. "Our homepage is algorithmic," Ek says. "If Glasvegas got there, it's because it was relevant to a Swedish audience, not because anyone in the company chose it. Record companies need to think about the way they break artists internationally. Why not just make the music free everywhere and see where it gets picked up? Who knows what will be huge in Sweden or Japan or Ukraine?"

Ek acknowledges that, without the far-reaching effects of The Pirate Bay and its ilk, Spotify could never have come to fruition. "There is a big file-sharing community here in Sweden," he says. "It's how people want to consume content. They don't want to be illegal, but they want to have everything at their fingertips instantly, which is what The Pirate Bay facilitated. The best way to compete with that is to come up with a better product. Spotify exists because of piracy."

***

Technology must be in the Swedish genes; in 1900, Stockholm had more telephones than London or Berlin. When Crown Princess Victoria announced her engagement last week, she did so via a video on the royal website. The weekend's biggest film opening was an adaptation of novelist Stieg Larsson's thriller The Girl with the Dragon Tattoo. The heroine of the title is a young computer hacker with a flexible attitude to the law.

It's easy to elicit sympathy for such a character when some two million Swedes use The Pirate Bay. Hence, perhaps, the support its creators received during their trial. Warg, Sunde and Neij (and Carl Lundstrom, a major donor to the site) are accused of being accessories to copyright infringement. They face a fine of 120m kronor (£9.6m) and up to two years in prison if they lose.

However, The Pirate Bay doesn't actually host any illegal copies of films or music; it merely points users towards file-sharing sources elsewhere on the web. For all their former pro-piracy bluster, The Pirate Bay's line of defence has been awfully prosaic. Lawyers acting on behalf of the entertainment industries must prove that the defendants have profited handsomely from the site's success. The trio insist that the few advertisements featured on the site fund only its (not inconsiderable) running costs.

On the trial's second day, the prosecution was forced to drop half the charges after it became clear that they had misunderstood the nature of BitTorrent technology; evidence they thought implicated The Pirate Bay did nothing of the sort. They also found it difficult to grasp the notion that the site is run as a collective rather than a hierarchical organisation. Indeed, if the Spectrial narrative (as written by the pirates) is to be believed, the film studios, record labels et al simply can't comprehend any project that operates outside the confines of a conventional business.

The Pirate Bay was set up by Piratbyran in 2003 as a way for the think tank – which opposes current intellectual property laws – to partake of a powerful new file-sharing method. The BitTorrent system works by sharing files not simply between two individual users, but among a swarm of downloaders, making sharing faster and more communal. "It was more effective than the previous technologies, so we wanted it to grow," say Tobias Andersson of Piratbyran, who gave evidence at the trial. "But we never imagined how much it would grow. By mid-2004, it was taking too much time and energy, so we handed it over to some friends who were dedicated tech guys – Peter, Fredrik and Gottfried."

Piratbyran and The Pirate Bay befriended one another online, from cities across Sweden. "We all came from the Swedish hacker scene," Andersson says. "It took three years for me to meet all the guys I work with. We just hung out online."

The advent of broadband in even the most northerly Swedish cities made such endeavours possible, but it also opened up a generation gap between the two sides of the online revolution, which has been thrown into relief by the trial. "We have some older supporters in court," Andersson says, "but last week was [half-term], and it seemed like every 14-year-old in Stockholm came down to the courthouse to see their idols!"

Rick Falkvinge says membership of his Pirate Party – which is unaffiliated with Piratbyran, but shares its ideology – peaks among 18-year-olds, and that he has met brilliant, tech-savvy activists as young as 13. The youth sections of the country's eight main political parties, unlike their elders, have all declared themselves in favour of free file-sharing. One of the few artists to have condemned The Pirate Bay in public is Bjorn Ulvaeus of Abba.

In court, Sunde, 30, the public face of the site, delighted in teasing his opponents. During one exchange, the prosecutor tried to speak his language, asking when he had first met his colleagues "IRL" – in real life. "We don't use the expression IRL," Sunde retorted. "We use AFK – away from keyboard." It's difficult to imagine any of the defendants being AFK for long.

Sunde (who dropped out of high school, despite supposedly speaking seven languages and being four years ahead of his grade in maths) even "Twittered" live from the courtroom under his pseudonym "brokep". "We had some pizza after today's [proceedings]," read one whimsical tweet. "Met the opposing side and asked if they could pick up the check. They refused."

"This trial is about the establishment's fight to retake control of communication," says Falkvinge, "but even the monopoly on reporting from the trial is shattered by 20 or more live bloggers giving second-by-second updates; and even by the defendants themselves, who have their laptops in the courtroom. The establishment waits until the next morning to publish its thoughts, by which time it's old news."

Three leading Swedish media groups were banned from a pre-trial press conference. "We've done our best to turn it into a circus," Andersson says. "We don't take it that seriously; whatever happens, there will be an appeal and the case will go to a higher court. This trial is just good PR."

Regardless of the verdict, The Pirate Bay is likely to live on. Not only does the site have servers outside Sweden, but Warg and Neij now live in Cambodia and Laos respectively.

One other thing is certain; piracy and file-sharing will become an election issue in Sweden. In early 2006, the Pirate Party was a fledgling group of fewer than 1,000 members; few media outlets took it seriously. Then, on 31 May that year, Swedish police raided the headquarters of The Pirate Bay, briefly confiscating the site's servers and beginning the legal process that led to the trial. "Suddenly," says Falkvinge, "we were handing out press releases like candy, everybody started calling us, and my face was on every newscast."

Today, the Pirate Party has a membership of 11,000 – more than two of the parties in parliament. Though it failed to win any seats in the 2006 general election, Falkvinge is confident his organisation can win a place in the European Parliament on 20 May. Courtesy of the internet's connective power, the Swedish Pirate Party already has international franchises on six continents.

Falkvinge, a red-haired, occasionally fiery 37-year-old, was formerly a project leader for Microsoft in Stockholm. He carries a netbook mini-laptop with him to show off his "pretty pictures" – graphs that demonstrate the growth in support for the Pirate Party, which, he claims, is a civil liberties movement. "Whichever way the trial goes, it will escalate the conflict," he says. "If they're acquitted, the [entertainment industry] lobby will scream for harsher laws. If they're convicted, there will be public outcry. Either way, it will end up in the political arena, just ahead of the European elections. That's where we come in."

Falkvinge enjoys discussing history – of the printing press, of copyright law, of Swedish politics. The popularity of his party helped to persuade both prime ministerial candidates in the last general election to state publicly that filesharing should remain legal. The country's advanced technological infrastructure and the activity – legal or illegal – that it generated have already changed the political conversation in Sweden. Soon the chatter will spread.

***

Ola Sars is a Harvard business graduate with a hipster sensibility. With three fellow thirtysomething Stockholmers, he set up a company called Tonium in 2006 to create the Pacemaker, a palm-sized MP3 mixing desk. The DJ mixes made by its users can be uploaded and shared. "Within three years, everything is going to be accessible, on your laptop, cellphone, wherever," Sars says. "The most important thing is a filter, and we think the human being is the most interesting and effective filter, better than any algorithm. When it comes to music, the DJ is the natural example of that." The idea behind the Pacemaker, he explains, was to democratise DJ culture. "We want to encourage taste-sharing in our community. We work with superstar DJs, but the Pacemaker isn't for them, it's for regular boys and girls."

Sweden has long been held up as a model of social democracy. So is there something in the mindset that predisposes the Swedes to the provision of free, communal culture online? "There's a law [Allemansratten] that I think is unique to Sweden, about common spaces," says Andersson. "You can go out camping in nature anywhere in Sweden without asking the landowner's permission. That sort of attitude predominates here."

It is perhaps not surprising, then, that many of the most successful Swedish internet exports have been social tools, such as Skype, Kazaa and Spotify. "To my knowledge, there's at least 40 sites already built for sharing Spotify playlists, independent of us," Ek says. One of the most popular is the Swedish site Spotylist.com. Another Swedish developer has built a software application that turns Nokia cellphones into Spotify remote controls.

"The Swedish mindset wants to provide a social security system," Sars says. "We want the national economy to balance out and allow everyone an equal life. Our big companies are capitalistic in their growth, but they stay and pay their taxes in Sweden. We've always bragged about having free hospitals, universities, and so on. Everything goes towards supporting that bigger cause. Corporate leaders in Sweden talk about the fact that they are doing business in order to employ people and support the welfare system. It's a naive idea, but a nice one, and it keeps driving the quest to find the next Swedish success."

Free for all: Stockholm's trailblazers

Skype

What does it do? Users download the program for free, and talk to other Skype users via a live video and audio feed. They can also text and call landlines for a discounted price. The feed can be unpredictable and is highly dependent on the user's computer and, of course, broadband link.

Who's behind it? Niklas Zennstrom, Janus Friis and a team of software developers based in Tallinn, Estonia.

When did it start? 2003

How many people use it? 405 million

Spotify

What does it do? Allows instant access to a huge online database of music – for free. The music is streamed, meaning that you do not have to download the track first and can never "own" the file or load it on to an MP3 player. One short advert is played per hour. Pay a £9.99 monthly fee and you don't get the adverts. The tracks are licensed from the artists' record companies, who get paid out of the website's ad revenues.

Who's behind it? Daniel Ek and Martin Lorentzon

When did it start? 2008

How many people use it? One million

The Pirate Bay

What does it do? It is essentially a message-board that lists useful links to BitTorrent files. First, you type in the name of a film, song, television show etc. Then click on the link, download the BitTorrent file, and your computer then finds and downloads dozens of small files from different users around the world, to form a complete movie. Usually illegal.

Who's behind it? The Swedish file-sharing advocacy group Piratbyran ("The Piracy Bureau"). The website is currently run independently, by Gottfrid Svartholm, Fredrik Neij and Peter Sunde, all three of whom are currently on trial.

When did it start? 2003

How many people use it? 25 million

Joost

What does it do? Allows subscribers to watch full-screen, broadcast-quality television on demand, chosen from more than 1000 channels, including CNN, MTV and the Comedy Channel. The service uses live streaming technology of the kind employed by YouTube, although its programmes are interrupted by adverts.

Who's behind it? Niklas Zennstrom and Janus Friis (the founders of Skype and Kazaa).

When did it start? 2007

How many people use it? 3.5 million

Kazaa

What does it do? Users download special software (known as a Fast-Track protocol) to share “peer topeer” (ie, swap with each other) video and music files. Has been sued repeatedly by the music industry for breach of copyright.

Who’s behind it ?Niklas Zennstrom,Janus Friis andPriit Kasesalu

When did it start? 2001

How many peopleuse it? Five million