USe AVPlayer to play mp3 file from url

-(void)playselectedsong{

    AVPlayer *player = [[AVPlayer alloc]initWithURL:[NSURL URLWithString:urlString]];
    self.songPlayer = player;
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(playerItemDidReachEnd:)
                                                 name:AVPlayerItemDidPlayToEndTimeNotification
                                               object:[songPlayer currentItem]];
    [self.songPlayer addObserver:self forKeyPath:@"status" options:0 context:nil];
    [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateProgress:) userInfo:nil repeats:YES];

    [self.songPlayer play];

}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

    if (object == songPlayer && [keyPath isEqualToString:@"status"]) {
        if (songPlayer.status == AVPlayerStatusFailed) {
            NSLog(@"AVPlayer Failed");

        } else if (songPlayer.status == AVPlayerStatusReadyToPlay) {
            NSLog(@"AVPlayerStatusReadyToPlay");


        } else if (songPlayer.status == AVPlayerItemStatusUnknown) {
            NSLog(@"AVPlayer Unknown");

        }
    }
}

- (void)playerItemDidReachEnd:(NSNotification *)notification {

 //  code here to play next sound file

}
Answer from Sumit Mundra on Stack Overflow
Top answer
1 of 3
7

USe AVPlayer to play mp3 file from url

-(void)playselectedsong{

    AVPlayer *player = [[AVPlayer alloc]initWithURL:[NSURL URLWithString:urlString]];
    self.songPlayer = player;
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(playerItemDidReachEnd:)
                                                 name:AVPlayerItemDidPlayToEndTimeNotification
                                               object:[songPlayer currentItem]];
    [self.songPlayer addObserver:self forKeyPath:@"status" options:0 context:nil];
    [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateProgress:) userInfo:nil repeats:YES];

    [self.songPlayer play];

}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

    if (object == songPlayer && [keyPath isEqualToString:@"status"]) {
        if (songPlayer.status == AVPlayerStatusFailed) {
            NSLog(@"AVPlayer Failed");

        } else if (songPlayer.status == AVPlayerStatusReadyToPlay) {
            NSLog(@"AVPlayerStatusReadyToPlay");


        } else if (songPlayer.status == AVPlayerItemStatusUnknown) {
            NSLog(@"AVPlayer Unknown");

        }
    }
}

- (void)playerItemDidReachEnd:(NSNotification *)notification {

 //  code here to play next sound file

}
2 of 3
4

its very simple Use AVAudioPlayer,take object as AVAudioPlayer *audioPlayer,

  NSURL *url = [NSURL URLWithString:@"http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8"];
  NSData *soundData = [NSData dataWithContentsOfURL:url];
  audioPlayer = [[AVAudioPlayer alloc] initWithData:soundData  error:NULL];
  audioPlayer.delegate = self;
  [audioPlayer play];

write below delegate Methods:

 -(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
    [audioPlayer stop];
     NSLog(@"Finished Playing");
  }

 - (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error
 {
  NSLog(@"Error occured");
 }
🌐
Jumpshare
jumpshare.com › viewer › audio
Audio Player - Play Audio File Online for Free | Jumpshare
Play your audio file on any device, wherever you find yourself. Our web-based viewer has a responsive design that gets along perfectly with commonly used desktop and mobile browsers. Send your audio file to anyone in a snap, using a secure link or email. No matter which device your recipients are using, they can view the file online without needing any app or a Jumpshare account. Listen to your audio file at speeds ranging from 0.5x to 2x.
Discussions

Play audio from URL
Please tell me and, if possible, provide a working code with comments that could play audio from the buffer? The question is that I found a working code that writes an audio stream to an mp3 file: import requests stream_url = 'https://ep256.hostingradio.ru:8052/europaplus256.mp3' r = ... More on discuss.python.org
🌐 discuss.python.org
0
0
January 3, 2022
Play mp3 via url only
I am looking for an extension that I can play mp3 audio via a url link whether this audio is from YouTube or etc... I searched well before asking my question here. All I found was an old add-on that doesn't work and an add-on that plays 360 video. More on community.appinventor.mit.edu
🌐 community.appinventor.mit.edu
0
1
February 21, 2025
Play Audio in Mobile App using URL | OutSystems
How to Play audio from URL like "https://www.noiseaddicts.com/samples_1w72b820/2242.mp3" · There are many topics on playing audio but nothing seems working. I want to play an audio on clicking play button. Please Help More on outsystems.com
🌐 outsystems.com
how to play audio file from url in android - Stack Overflow
I need to play audio file from remote server in my app. I could play when I tested with localhost server (using WAMP). When the same file supplied from the server it is not working.. The file has no extension and the content is MP3 · String fileUrl = "http://192.168.1.131/myproject/songs/xyz"; String url ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Python.org
discuss.python.org › python help
Play audio from URL - Python Help - Discussions on Python.org
January 3, 2022 - Please tell me and, if possible, provide a working code with comments that could play audio from the buffer? The question is that I found a working code that writes an audio stream to an mp3 file: import requests stream_url = 'https://ep256.hostingradio.ru:8052/europaplus256.mp3' r = requests.get(stream_url, stream=True) with open('stream.mp3', 'wb') as f: try: for block in r.iter_content(1024): f.write(block) except KeyboardInterrupt: pass I thought that...
🌐
MIT App Inventor
community.appinventor.mit.edu › mit app inventor help
Play mp3 via url only - MIT App Inventor Help - MIT App Inventor Community
February 21, 2025 - I am looking for an extension that I can play mp3 audio via a url link whether this audio is from YouTube or etc... I searched well before asking my question here. All I found was an old add-on that doesn't work and an …
🌐
Amazingaudioplayer
amazingaudioplayer.com › html5-audio-player › how-to-play-different-mp3-files-by-passing-a-url-parameter
How to play different mp3 files by passing a URL parameter | HTML5 Audio Player for Your Website
First, create a player, then rename or copy the generated audioplayer.html to audioplayer.php. Add the following code to the beginning of the webpage: <?php $audioTitle = "Chapter 1"; $audioUrl = "https://amazingaudioplayer.com/demo/prideandprejudice_01.mp3"; if ( !empty( $_GET["audio"] ) ) { switch( $_GET["audio"] ) { case 1: $audioTitle = "Chapter 1"; $audioUrl = "https://amazingaudioplayer.com/demo/prideandprejudice_01.mp3"; break; case 2: $audioTitle = "Chapter 2"; $audioUrl = "https://amazingaudioplayer.com/demo/prideandprejudice_02.mp3"; break; case 3: $audioTitle = "Chapter 3"; $audioUrl = "https://amazingaudioplayer.com/demo/prideandprejudice_03.mp3"; break; case 4: $audioTitle = "Chapter 4"; $audioUrl = "https://amazingaudioplayer.com/demo/prideandprejudice_04.mp3"; break; } } ?>
Find elsewhere
🌐
Linkqr
linkqr.id › media-player
Online MP4 & MP3 Player - Play Video & Audio | LinkQR.ID
Play MP4 video or MP3 audio directly from URL online. Just paste your media link and hit play. Fast, lightweight, and free.
🌐
GitHub
github.com › naudio › NAudio › blob › master › Docs › PlayAudioFromUrl.md
NAudio/Docs/PlayAudioFromUrl.md at master · naudio/NAudio
In this example designed to be run from a console app, we use MediaFoundationReader to load the audio from the network and then simply block until playback has finished. var url = "http://media.ch9.ms/ch9/2876/fd36ef30-cfd2-4558-8412-3cf7a0852876/AzureWebJobs103.mp3"; using(var mf = new MediaFoundationReader(url)) using(var wo = new WasapiOut()) { wo.Init(mf); wo.Play(); while (wo.PlaybackState == PlaybackState.Playing) { Thread.Sleep(1000); } }
Author   naudio
🌐
Computer Hope
computerhope.com › issues › ch000071.htm
How to Create a Link to Play a Sound File in HTML
January 6, 2025 - With HTML (HyperText Markup Language), linking a sound file using a href allows a browser to open and play an audio file if the viewer of your web page has properly configured their Internet browser.
Top answer
1 of 5
17

If you happen to have VLC installed (or are willing to install it), then this should work:

import vlc
p = vlc.MediaPlayer("http://your_mp3_url")
p.play()

This has the advantage that it works with everything VLC works with, not just MP3. It can also be paused if you want to.

You can install vlc for python using

pip install python-vlc
2 of 5
3

Sorry but I do not have Python3 to test here, to stream mp3 using pyaudio you will need decode it in PCM data, I know that pymedia can do it, but it is too old and just support python27.

To do this the right way you will need to know some attributes of your audio, things like samplerate, number of channels, bit resolution, to set it in the pyaudio.

I can show how I do it using python27 + pyaudio, first I will show how it is done to stream .wav

from urllib2 import urlopen
#to python3.x
#from urllib.request import urlopen
import pyaudio


pyaud = pyaudio.PyAudio()

srate=44100

stream = pyaud.open(format = pyaud.get_format_from_width(1),
                channels = 1,
                rate = srate,
                output = True)


url = "http://download.wavetlan.com/SVV/Media/HTTP/WAV/NeroSoundTrax/NeroSoundTrax_test4_PCM_Mono_VBR_8SS_44100Hz.wav"
u = urlopen(url)

data = u.read(8192)

while data:

    stream.write(data)
    data = u.read(8192)

choose large buffer, python is slow in while loop, i did it using chunks of size 8192, note that format, channels and rate are the rigth attributes for this wav file, so for .wav we not need decode, it is a PCM data, now for mp3 we will need decode and put in PCM format to stream.

Lets try using pymedia

from urllib2 import urlopen
import pyaudio
import pymedia.audio.acodec as acodec
import pymedia.muxer as muxer
dm= muxer.Demuxer( 'mp3' )


pyaud = pyaudio.PyAudio()

srate=44100

stream = pyaud.open(format = pyaud.get_format_from_width(2),
                channels = 1,
                rate = srate,
                output = True)


url = "http://www.bensound.org/bensound-music/bensound-dubstep.mp3"

u = urlopen(url)

data = u.read(8192)

while data:

    #Start Decode using pymedia
    dec= None
    s= " "
    sinal=[]
    while len( s ):
        s= data
        if len( s ):
            frames= dm.parse( s )
            for fr in frames:
                if dec== None:
                    # Open decoder
                    dec= acodec.Decoder( dm.streams[ 0 ] )
                r= dec.decode( fr[ 1 ] )
                if r and r.data:
                    din = r.data;
            s=""
    #decode ended

    stream.write(din)
    data = u.read(8192)

This may be secret, because I never saw anyone showing how this can be done in python, for python3 I not know anything that can decode .mp3 into pieces like pymedia do.

Here these two codes are streming and working for .wav and .mp3

🌐
GitHub
github.com › jfversluis › Plugin.Maui.Audio › issues › 13
Enable playing audio from a URL · Issue #13 · jfversluis/Plugin.Maui.Audio
August 19, 2022 - Plugin.Maui.Audio provides the ability to play audio inside a .NET MAUI application - Enable playing audio from a URL · Issue #13 · jfversluis/Plugin.Maui.Audio
Author   jfversluis
🌐
Reddit
reddit.com › r/tasker › [feature request] play audio from url
r/tasker on Reddit: [Feature Request] Play audio from URL
November 11, 2022 -

I'd like to make Tasker play audio directly from a url, this applies to a lot of programs/podcats and other long audios you may want to listen to while you drive/commute/walk/on the go.

I think the way Tasker implemented the "Music Play Dir" action is the right way, meaning that the action will trigger the audio and will require another action to stop it, rather than keep the task alive and get Tasker stuck.

Yes, there are a lot of apps that could help in this regard but because this is a quite simple action and the fact that Tasker shines above all other apps is circumstances. All the other phone setup before you start listening, for me, it always disappointing to set everything up with Tasker and then launch 3rd party software that does one simple action.

🌐
CodePen
codepen.io › SitePoint › pen › JRaLVR
Playing an MP3 file with the Web Audio API
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.