how to play mp3 streaming in objectives c - ios

I have this stream url with mp3 type: http://www.slobodnyvysielac.sk/redata/other/play.php?file=informacna%20vojna%20-%202015-02-17%20financne%20skupiny.mp3
when I open this url with Safari or Chrome, it can play, but I can't play it with objectives C code (iOS).
Please tell me the solution!
Thanks all!

player = [[AVPlayer alloc] initWithURL:[NSURL URLWithString:#"http://archive.slobodnyvysielac.sk/informacna%20vojna%20-%202015-02-10%20hudo.mp3"]];
[player play];
Inside your view controller or whatever class you have define this, don't define it inside the event where you stream.
AVPlayer *player
EDIT:
There was a problem with your URL, if you open it in the browser, it opens a flash player so I inspected the flash object and got the original MP3 url which will stream, and you can compare how Google Chrome e.g. reacts to both URLs to notice the difference, now the url in my above code is the correct one

Related

YTPlayerView not playing video with Youtube URL

I am using YTPlayerView for playing embedded videos in my app. Everything works perfect with ID but video doesn't play with URL. Here is my code
-(IBAction)playVideo:(id)sender{
self.playerView.delegate = self;
self.playerView.hidden = false;
[self.playerView loadVideoByURL:#"https://www.youtube.com/watch?v=KWTULSf29Ho" startSeconds:0 suggestedQuality:kYTPlaybackQualitySmall];
}
The URL has to be in the format youtube.com/v/VIDEO_ID?version=3, your url was wrong.
if you want to achieve the specific format, change your method which for responding user input url, appending ?version=3 with user input url.
check this,i think you forgot load the video into the player

How to play an array of songs using streamingkit library

Has anyone out there ever used this https://github.com/tumtumtum/StreamingKit/ package to play remote mp3 files? How can one load an array of music urls and play them one after the other?
Just as document says:
STKAudioPlayer* audioPlayer = [[STKAudioPlayer alloc] init];
[audioPlayer queue:#"http://www.abstractpath.com/files/audiosamples/sample.mp3"];
[audioPlayer queue:#"http://www.abstractpath.com/files/audiosamples/airplane.aac"];
You just need to add url to queue.

Stream video while downloading iOS

I am using iOS 7 and I have a .mp4 video that I need to download in my app. The video is large (~ 1 GB) which is why it is not included as part of the app. I want the user to be able to start watching the video as soon as is starts downloading. I also want the video to be able to be cached on the iOS device so the user doesn't need to download it again later. Both the normal methods of playing videos (progressive download and live streaming) don't seem to let you cache the video, so I have made my own web service that chunks up my video file and streams the bytes down to the client. I start the streaming HTTP call using NSURLConnection:
self.request = [[NSMutableURLRequest alloc] initWithURL:self.url];
[self.request setTimeoutInterval:10]; // Expect data at least every 10 seconds
[self.request setHTTPMethod:#"GET"];
self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:YES];
When I receive a data chunk, I append it to the end of the local copy of the file:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:[self videoFilePath]];
[handle truncateFileAtOffset:[handle seekToEndOfFile]];
[handle writeData:data];
}
If I let the device run, the file is downloaded successfully and I can play it using MPMoviePlayerViewController:
NSURL *url=[NSURL fileURLWithPath:self.videoFilePath];
MPMoviePlayerViewController *controller = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
controller.moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
[self presentMoviePlayerViewControllerAnimated:controller];
However, if I start the player before the file is completely downloaded, the video starts playing just fine. It even has the correct video length displayed at the top scrubber bar. But when the user gets to the position in the video that I had completed downloading before the video started, the video just hangs. If I close and reopen the MPMoviePlayerViewController, then the video plays until it gets to whatever location I was then at when I launched the MPMoviePlayerViewController again. If I wait until the entire video is downloaded, then the video plays without a problem.
I am not getting any events fired, or error messages printed to the console when this happens (MPMoviePlayerPlaybackStateDidChangeNotification and MPMoviePlayerPlaybackDidFinishNotification are never sent after the video starts). It seems like there is something else that is telling the controller what the length of the video is other than what the scrubber is using...
Does anyone know what could be causing this issue? I am not bound to using MPMoviePlayerViewController, so if a different video playback method would work in this situation I am all for it.
Related Unresolved Questions:
AVPlayer and Progressive Video Downloads with AVURLAssets
Progressive Video Download on iOS
How to play an in downloading progress video file in IOS
UPDATE 1
I have found that the video stall is indeed because of the file size when the video starts playing. I can get around this issue by creating a zero-ed out file before I start the download and over overwrite it as I go. Since I have control over the video streaming server, I added a custom header so I know the size of the file being streamed (default file size header for a streaming file is -1). I am creating the file in my didReceiveResponse method as follows:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// Retrieve the size of the file being streamed.
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSDictionary *headers = httpResponse.allHeaderFields;
NSNumberFormatter * formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
self.streamingFileSize = [formatter numberFromString:[headers objectForKey:#"StreamingFileSize"]];
// Check if we need to initialize the download file
if (![[NSFileManager defaultManager] fileExistsAtPath:self.path])
{
// Create the file being downloaded
[[NSData data] writeToFile:self.path atomically:YES];
// Allocate the size of the file we are going to download.
const char *cString = [self.path cStringUsingEncoding:NSASCIIStringEncoding];
int success = truncate(cString, self.streamingFileSize.longLongValue);
if (success != 0)
{
/* TODO: handle errors here. Probably not enough space... See 'man truncate' */
}
}
}
This works great, except that truncate causes the app to hang for about 10 seconds while it creates the ~1GB file on disk (on the simulator it is instant, only a real device has this problem). This is where I am stuck now - does anyone know of a way to allocate a file more efficiently, or a different way to get the video player to recognize the size of the file without needing to actually allocate it? I know some filesystems support "file size" and "size on disk" as two different properties... not sure if iOS has something like that?
I figured out how to do this, and it is much simpler than my original idea.
First, since my video is in .mp4, the MPMoviePlayerViewController or AVPlayer class can play it directly from a web server - I don't need to implement anything special and they can still seek to any point in the video. This must be part of how the .mp4 encoding works with the movie players. So, I just have the raw file available on the server - no special headers required.
Next, when the user decides to play the video I immediately start playing the video from the server URL:
NSURL *url=[NSURL fileURLWithPath:serverVidelFileURLString];
controller = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
controller.moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
[self presentMoviePlayerViewControllerAnimated:controller];
This makes it so the user can watch the video and seek to any location they want. Then, I start downloading the file manually using NSURLConnection like I had been doing above, except now I am not streaming the file, I just download it directly. This way I don't need the custom header since the file size is included in the HTTP response.
When my background download completes, I switch the playing item from the server URL to the local file. This is important for network performance because the movie players only download a few seconds ahead of what the user is watching. Being able to switch to the local file as soon as possible is key to avoid downloading too much duplicate data:
NSTimeInterval currentPlaybackTime = videoController.moviePlayer.currentPlaybackTime;
[controller.moviePlayer setContentURL:url];
[controller.moviePlayer setCurrentPlaybackTime:currentPlaybackTime];
[controller.moviePlayer play];
This method does have the user downloading two video files at the same time initially, but initial testing on the network speeds my users will be using shows it only increases the download time by a few seconds. Works for me!
You gotta create an internal webserver that acts like a proxy! Then set your player to play the movie from the localhost.
When using HTTP protocol to play a video with MPMoviePlayerViewController, the first thing the player does is to ask for the byte-range 0-1 (first 2 bytes) just to obtain the file length. Then, the player asks for "chunks" of the video using the "byte-range" HTTP command (the purpose is to save some battery).
What you have to do is to implement this internal server that delivers the video to the player, but your "proxy" must consider the length of your video as the full length of the file, even if the actual file hasn't been completely downloaded from the internet.
Then you you set your player to play a movie from " http:// localhost : someport "
I've done this before... it works perfectly!
Good luck!
I can only assume that the MPMoviePlayerViewController caches the file length of the file when you started it.
The way to fix (just) this issue is to first determine how large the file is. Then create a file of that length. Keeping an offset pointer, as the file downloads, you can overwrite the "null" values in the file with the real data.
So you get to a specific point in the download, start the MPMoviePlayerViewController, and let it run. I'd also suggest you use the "F_NOCACHE" flag (with fcntl()) so you bypass the file block cache (which means you will lower your memory footprint).
The downside to this architecture is that if you get stalled, and the movie player gets ahead of you, well, the user is going to have a pretty bad experience. Not sure if there is any way for you to monitor and take preemptive action.
EDIT: its quite possible that the video is not read sequentially, but certain information requires the player to essentially look ahead for something. If so, then this is doomed to fail. The only other possible solution is to use some software tool to sequentially order the file (I'm no video expert so cannot comment from experience on any of the above).
To test this out, you can construct a "damaged" video of varying lengths, and test that to see what works and what does not. For instance, suppose you have a 100Meg file. Write a little utility program, and over write the last 50Megs of data with zeros. Now play this video. Its should fail 1/2 through. If it fails right away, well, you now know that its seeking in the file.
If non sequential, its possible that its looking at the last 1000 bytes or so, in which case if you don't overwrite that things work as you want. If you get lucky and this is the case, you would eventually download the last 1000 bytes, then then start from the front of the file.
It really gets down to finding some way before introducing real networking into the picture, to play a partial file. You will surely find it easier to artificially introduce the networking conditions without really doing it real time.

How to refresh the .m3u8 file, ie., the url used by the AVPlayer in case of Live broadcast?

I have used an AVPlayer object to fetch the .m3u8 file from a remote server and play the video. My application has to stream live data, wherein the .m3u8 file would be updated (either new .ts files are added to the existing contents or the old ones are removed prior adding new .ts files) regularly. How do I make my AVPlayer respond to changing contents on server data. Precisely how to re-assign the url to AVPlayer. Below is the concise code. Please advise.
-(void) playVideo{
AVPlayerItem *contentPlayerItem = [[AVPlayerItem alloc]initWithURL:[NSURL URLWithString:contentURL]]; // contentURL contains the path of live streaming data.
self.contentPlayer = [AVPlayer playerWithPlayerItem:contentPlayerItem]; //content player is an object of type AVPlayer
AVPlayerLayer *avPlayerLayer =
[AVPlayerLayer playerLayerWithPlayer:self.contentPlayer];
//Then I add the AVPlayerLayer object onto my current view after setting its frame.
}
The question is when and how do I refresh the url, assuming the video is being played currently?

AVPlayer how to manage different URL

I'm trying to do a small radio app and I got a list of URL that I pass to AVPlayer but I can't understand how to manage different URL.
As example if I first play this URL: http://www.example.com/file.mp3
then I call http://www.example.net/file2.mp3
it works fine but when I select http://www.example.org/file.mp3.m3u it doesn't load that URL and AVPlayer won't play.
This is the code I use:
urlStream = [NSURL URLWithString:mp3URL];
appDelegate = [[UIApplication sharedApplication]delegate];
playerItem = [AVPlayerItem playerItemWithURL:urlStream];
playerItem addObserver:self forKeyPath:#"playbackBufferEmpty" options:NSKeyValueObservingOptionNew context:nil];
[playerItem addObserver:self forKeyPath:#"playbackLikelyToKeepUp" options:NSKeyValueObservingOptionNew context:nil];
[appDelegate.player replaceCurrentItemWithPlayerItem:playerItem];
I use replaceCurrentItemWithPlayerItem:playerItem because if I use initWithPlayerItem when I choose another stream I just can't stop the previous play: so the only way to stop the playing stream and start another one is to use replaceCurrentItemWithPlayerItem.
In the Apple documentation I read that replaceCurrentItemWithPlayerItem must have the same "compositor" as the items it replaces: what's a compositor?
I see that what it's different between the first two streams and the third (in the example above) is the file extension.
Any suggestion where to look for would be greatly appreciated.
The problem appears not to be the replacing of items - but the file format of particular files. Try to open the m3u file first - probably it will fail as well.
The m3u-URL indicates that this not an mp3 file but a m3u file - that's a list of URLs to media files. AVPlayer and AVPlayerItem are capable of playing m3u8 files - that are m3u files which are UTF8-encoded.
Have you tried opening those URLs in Mobile Safari? If they don't work there the format probably is not supported by AVPlayer either.
In any case - if you could provide the actual problematic URL one could check the actual file format.
With "compositor" the "Quartz compositor" is meant - forget about that, not relevant here.
[Edit: maybe it is relevant - I'm dumbfounded after you comment to this answer ...]

Resources