Play MP3 Files with iPhone SDK
These are the codes for the requested actions,
appSoundPlayer is a property of AVAudioPlayer declared in h file. Also this example plays a song in the resource folder.
#pragma mark -
#pragma mark *play*
- (IBAction) playaction {
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"songname" ofType:@"mp3"];
NSURL *newURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
self.soundFileURL = newURL;
[newURL release];
[[AVAudioSession sharedInstance] setDelegate: self];
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: nil];
// Registers the audio route change listener callback function
AudioSessionAddPropertyListener (
kAudioSessionProperty_AudioRouteChange,
audioRouteChangeListenerCallback,
self
);
// Activates the audio session.
NSError *activationError = nil;
[[AVAudioSession sharedInstance] setActive: YES error: &activationError];
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: soundFileURL error: nil];
self.appSoundPlayer = newPlayer;
[newPlayer release];
[appSoundPlayer prepareToPlay];
[appSoundPlayer setVolume: 1.0];
[appSoundPlayer setDelegate: self];
[appSoundPlayer play];
[stopbutton setEnabled:YES];
[playbutton setEnabled: NO];
playbutton.hidden=YES;
pausebutton.hidden =NO;
}//playbutton touch up inside
#pragma mark -
#pragma mark *pause*
-(IBAction)pauseaction {
[appSoundPlayer pause];
pausebutton.hidden = YES;
resumebutton.hidden = NO;
}//pausebutton touch up inside
#pragma mark -
#pragma mark *resume*
-(IBAction)resumeaction{
[appSoundPlayer prepareToPlay];
[appSoundPlayer setVolume:1.0];
[appSoundPlayer setDelegate: self];
[appSoundPlayer play];
playbutton.hidden=YES;
resumebutton.hidden =YES;
pausebutton.hidden = NO;
}//resumebutton touch up inside
#pragma mark -
#pragma mark *stop*
-(IBAction)stopaction{
[appSoundPlayer stop];
[playbutton setEnabled:YES];
[stopbutton setEnabled:NO];
playbutton.hidden=NO;
resumebutton.hidden =YES;
pausebutton.hidden = YES;
}//stopbutton touch up inside
How do I programmatically play an MP3 on an iPhone?
You could also try the AVAudioPlayer utility Framework.
How to play mp3 in iOS with Obj-C
Apple provide many ways to play audio on the iPhone – System Sound Services, AVAudioPlayer, Audio Queue Services, and OpenAL. Without outside support libraries, the two easiest ways by far are System Sound Services and AVAudioPlayer.
System Sound Services
It is useful for audio alerts and simple game sounds.
NSString *pewPewPath = [[NSBundle mainBundle]
pathForResource:@"pew-pew-lei" ofType:@"caf"];
NSURL *pewPewURL = [NSURL fileURLWithPath:pewPewPath];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)pewPewURL,
&self.pewPewSound);
AudioServicesPlaySystemSound(self.pewPewSound);
It is important to define pewPewSound as an iVar or property, and not as a local variable so that you can dispose of it later in dealloc. It is declared as a SystemSoundID.
If you were to dispose of it immediately after AudioServicesPlaySystemSound(self.pewPewSound), then the sound would never play.2. AVAudioPlayer
It allow to play several sounds at once (using a different AVAudioPlayer for each sound), and you can play sounds even when your app is in the background..The AVAudioPlayer class is part of AVFoundation, you will need to @import AVFoundation into your project.
NSError *error;
self.backgroundMusicPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:backgroundMusicURL error:&error];
[self.backgroundMusicPlayer prepareToPlay];
[self.backgroundMusicPlayer play];
ATBViewController.h
#import <UIKit/UIKit.h>
@interface ATBViewController : UIViewController
@end
ATBViewController.m
#import "ATBViewController.h"
#import "AudioController.h"
@interface ATBViewController ()
@property (strong, nonatomic) AudioController *audioController;
@end
@implementation ATBViewController
#pragma mark - Lifecycle
- (void)viewDidLoad {
[super viewDidLoad];
self.audioController = [[AudioController alloc] init];
[self.audioController tryPlayMusic];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - IBAction
- (IBAction)spaceshipTapped:(id)sender {
//The call below uses AudioServicesPlaySystemSound to play
//the short pew-pew sound.
[self.audioController playSystemSound];
[self fireBullet];
}
- (void)fireBullet {
// In IB, the button to top layout guide constraint is set to 229, so
// the bullets appear in the correct place, on both 3.5" and 4" screens
UIImageView *bullets = [[UIImageView alloc] initWithFrame:CGRectMake(84, 256, 147, 29)];
bullets.image = [UIImage imageNamed:@"bullets.png"];
[self.view addSubview:bullets];
[self.view sendSubviewToBack:bullets];
[UIView beginAnimations:@"shoot" context:(__bridge void *)(bullets)];
CGRect frame = bullets.frame;
frame.origin.y = -29;
bullets.frame = frame;
[UIView setAnimationDuration:0.5];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
[UIView commitAnimations];
}
- (void) animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
UIImageView *bullets = (__bridge UIImageView *)context;
[bullets removeFromSuperview];
}
@end
AudioController.h
#import <Foundation/Foundation.h>
@interface AudioController : NSObject
- (instancetype)init;
- (void)tryPlayMusic;
- (void)playSystemSound;
@end
AudioController.m
#import "AudioController.h"
@import AVFoundation;
@interface AudioController () <AVAudioPlayerDelegate>
@property (strong, nonatomic) AVAudioSession *audioSession;
@property (strong, nonatomic) AVAudioPlayer *backgroundMusicPlayer;
@property (assign) BOOL backgroundMusicPlaying;
@property (assign) BOOL backgroundMusicInterrupted;
@property (assign) SystemSoundID pewPewSound;
@end
@implementation AudioController
#pragma mark - Public
- (instancetype)init
{
self = [super init];
if (self) {
[self configureAudioSession];
[self configureAudioPlayer];
[self configureSystemSound];
}
return self;
}
- (void)tryPlayMusic {
// If background music or other music is already playing, nothing more to do here
if (self.backgroundMusicPlaying || [self.audioSession isOtherAudioPlaying]) {
return;
}
[self.backgroundMusicPlayer prepareToPlay];
[self.backgroundMusicPlayer play];
self.backgroundMusicPlaying = YES;
}
- (void)playSystemSound {
AudioServicesPlaySystemSound(self.pewPewSound);
}
#pragma mark - Private
- (void) configureAudioSession {
// Implicit initialization of audio session
self.audioSession = [AVAudioSession sharedInstance];
NSError *setCategoryError = nil;
if ([self.audioSession isOtherAudioPlaying]) { // mix sound effects with music already playing
[self.audioSession setCategory:AVAudioSessionCategorySoloAmbient error:&setCategoryError];
self.backgroundMusicPlaying = NO;
} else {
[self.audioSession setCategory:AVAudioSessionCategoryAmbient error:&setCategoryError];
}
if (setCategoryError) {
NSLog(@"Error setting category! %ld", (long)[setCategoryError code]);
}
}
- (void)configureAudioPlayer {
// Create audio player with background music
NSString *backgroundMusicPath = [[NSBundle mainBundle] pathForResource:@"background-music-aac" ofType:@"caf"];
NSURL *backgroundMusicURL = [NSURL fileURLWithPath:backgroundMusicPath];
self.backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:backgroundMusicURL error:nil];
self.backgroundMusicPlayer.delegate = self; // We need this so we can restart after interruptions
self.backgroundMusicPlayer.numberOfLoops = -1; // Negative number means loop forever
}
- (void)configureSystemSound {
NSString *pewPewPath = [[NSBundle mainBundle] pathForResource:@"pew-pew-lei" ofType:@"caf"];
NSURL *pewPewURL = [NSURL fileURLWithPath:pewPewPath];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)pewPewURL, &_pewPewSound);
}
#pragma mark - AVAudioPlayerDelegate methods
- (void) audioPlayerBeginInterruption: (AVAudioPlayer *) player {
self.backgroundMusicInterrupted = YES;
self.backgroundMusicPlaying = NO;
}
- (void) audioPlayerEndInterruption: (AVAudioPlayer *) player withOptions:(NSUInteger) flags{
[self tryPlayMusic];
self.backgroundMusicInterrupted = NO;
}
@end
How to play mp3 audio from URL in iOS Swift?
I tried the following:-
let urlstring = "http://radio.spainmedia.es/wp-content/uploads/2015/12/tailtoddle_lo4.mp3"
let url = NSURL(string: urlstring)
print("the url = \(url!)")
downloadFileFromURL(url!)
Add the below methods:-
func downloadFileFromURL(url:NSURL){
var downloadTask:NSURLSessionDownloadTask
downloadTask = NSURLSession.sharedSession().downloadTaskWithURL(url, completionHandler: { [weak self](URL, response, error) -> Void in
self?.play(URL)
})
downloadTask.resume()
}
And your play method as it is:-
func play(url:NSURL) {
print("playing \(url)")
do {
self.player = try AVAudioPlayer(contentsOfURL: url)
player.prepareToPlay()
player.volume = 1.0
player.play()
} catch let error as NSError {
//self.player = nil
print(error.localizedDescription)
} catch {
print("AVAudioPlayer init failed")
}
}
Download the mp3 file and then try to play it, somehow AVAudioPlayer does not download your mp3 file for you. I am able to download the audio file and player plays it.
Remember to add this in your info.plist since you are loading from a http source and you need the below to be set for iOS 9+
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
</plist>
How to play a sound on iOS 11 with swift 4? And where i place The mp3 file?
SWIFT 4 / XCODE 9.1
import AVFoundation
var objPlayer: AVAudioPlayer?
func playAudioFile() {
guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
// For iOS 11
objPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
// For iOS versions < 11
objPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3)
guard let aPlayer = objPlayer else { return }
aPlayer.play()
} catch let error {
print(error.localizedDescription)
}
}
Can I stream mp3 files in my iOS app? Or do I have to download the content locally?
Yes, you can just use an MPMoviePlayerViewController
and set the content URL to the URL of the remote media (video or audio).
AVAudioPlayer cannot play MP3 file
Its working fine for me. check below code
Objective C
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()
{
AVAudioPlayer *_audioPlayer;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Construct URL to sound file
NSString *path = [NSString stringWithFormat:@"%@/yellow.mp3", [[NSBundle mainBundle] resourcePath]];
NSURL *soundUrl = [NSURL fileURLWithPath:path];
// Create audio player object and initialize with URL to sound
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
[_audioPlayer play];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
Swift
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let audioPath = NSBundle.mainBundle().pathForResource("yellow", ofType: "mp3")
do {
audioPlayer = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath!))
audioPlayer .play()
}
catch {
print("Something bad happened. Try catching specific errors to narrow things down")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
AVAudioPlayer doesn't play mp3?
http://bugreport.apple.com
Engineering has determined that this issue behaves as intended based on the following information:
Could repro with attached sample app, but this is an expected behavior from AudioFile.
The issue is that AVAudioPlayer
is being initialized with a url without a file extension and the corresponding file does not have a valid ID3
tag.Without a file extension or valid data, we cannot determine the right file format and hence such files will fail to open.This is an expected behavior.
In the sample code attached:
path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
path = [path stringByAppendingPathComponent:@"song"];
--> path will be something like:
/var/mobile/Applications/2FFD0147-E56B-47D4-B143-A9F19BE92818/Documents/song
--> NOTE: no file extension at the end.
abc.mp3 has an invalid ID3
tag size (0x2EE) unlike def.mp3 which has a valid tag size (0x927). Hence when these are specified as "…./song" without any extension, AudioFile just looks at the data and finds a valid sync word for def.mp3 but not for abc.mp3.
However, replacing stringByAppendingPathComponent:@"song"
with stringByAppendingPathComponent:@"song.mp3"
succeeds for abc.mp3, and could help for other mp3 files in general.
We consider this issue closed. If you have any questions or concern regarding this issue, please update your report directly (http://bugreport.apple.com).
Thank you for taking the time to notify us of this issue.
Playing Multiple MP3 files with Multiple Buttons - iPhone SDK - xCode
I believe that you should use AVAudioPlayer to play MP3 files instead of AudioServicesPlaySystemSound. AVAudioPlayer supports playing "...multiple sounds simultaneously, one sound per audio player, with precise synchronization". See the AVAudioPlayer Class Reference. Here's also a link to a project showing how you use AVAudioPlayer: [http://www.techotopia.com/index.php/Playing_Audio_on_an_iPhone_using_AVAudioPlayer_(iOS_4)][1]
Related Topics
How to Calculate Actual Font Point Size in iOS 7 (Not the Bounding Rectangle)
Setting "Applelanguages" Doesn't Change App Language
Singleton in iOS Objective C Doesn't Prevent More Than One Instance
How to Convert an Uiimage to Grayscale in Swift Using Cifilter
Conditionally Import a Framework (Such as Speech) Based on iOS Version in Swift
How to Edit Uialertaction Text Font Size and Color
How to Set Mime Type of Application/Vnd.Apple.Pkpass in Order to Share Pass by Link or Email
Google Places Autocomplete on iOS - Can't Load Search Results - Try Again
iOS Automatically Add Hyphen in Text Field
How to Get Word Wrap Information with the New iOS 7 APIs
Alamofire Download in Background Session
Aligning Right to Left on Uicollectionview
Xcode 6 Storyboard Unwind Segue with Swift Not Connecting to Exit
Drawviewhierarchyinrect:Afterscreenupdates: Delays Other Animations
How to Split String into Substrings on iOS
How to Make Uiimagepickercontroller for Camera and Photo Library at the Same Time in Swift