Search code examples
iosswiftmp3media-player

How do i stream a mp3 file with swift in an app?


I have an MP3 file, and I want to be able to play this file with 'Media Player' Framework. How do I upload this file onto a URL? I tried putting it on YouTube, then putting the YouTube URL in the app, but it does not work. What do I do?

Here is my code for the app:

import UIKit
import MediaPlayer

class AudioViewController: UIViewController {
    var movie:MPMoviePlayerViewController?

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
         self.playAudio("https://www.youtube.com/embed/tQsxOtH8-RQ")
    }

    func playAudio(URL:String){
        let movieurl:NSURL? = NSURL(string: "\(URL)")

        if movieurl != nil {
            self.movie = MPMoviePlayerViewController(contentURL: movieurl!)
        }

        if self.movie != nil {
            self.presentViewController(self.movie!, animated: true, completion: nil)
            self.movie?.moviePlayer.play()
        }
    }
}

Solution

  • Your code is fine. The code snippet below also works. The current problem you are experiencing is due to trying to play a youtube/vimeo stream in the MPMoviewPlayerViewController. If you want to stream from those sites, you will have to use a UIWebView. There are some custom players on GitHub and elsewhere, but if you will use the snippet below and replace the URL with an mp3 hosted on your own site (i.e. WordPress) somewhere, it will play just fine.

    var url = NSURL(string: "non-youtube/vimeo URL")
    
    var mediaPlayerController = MPMoviePlayerViewController(contentURL: url)
    self.presentViewController(mediaPlayerController, animated: true, completion: nil)
    mediaPlayerController.moviePlayer.prepareToPlay()
    mediaPlayerController.moviePlayer.play()
    

    Hope this helps.

    FYI, make sure you add the MediaPlayer Framework and add the import MediaPlayer line to the top of your class.