Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
What's the easiest way to play a music file such as Mp3 with pause button?
very very simple a button play and another button pause that music
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
For short sounds or when the MP3 does not play well on the suggested code you can always use:
SystemSoundID soundID;
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/sound.mp3", [[NSBundle mainBundle] resourcePath]]];
AudioServicesCreateSystemSoundID((CFURLRef)url, &soundID);
AudioServicesPlaySystemSound (soundID);
Don't forget to add:
#import <AudioToolbox/AudioToolbox.h>
well here is a good tutorial available.
The theme is
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/audiofile.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = -1;
[audioPlayer play];
and when you want to pause;
[audioPlayer pause];
hope this helps.
I'm afraid the answer stated no longer works in iOS 7 and above. You will need to use the following code:
in the header file (.h)
In order to handle the delegate methods like when the playing of the audio has finished audioPlayerDidFinishPlaying:, inherit from AVAudioPlayerDelegate .
#property (nonatomic, strong) AVAudioPlayer *player;
in the implementation file (.m)
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: resourceName
ofType: #"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL
error: nil];
_player = newPlayer;
[_player prepareToPlay];
[_player setDelegate: self];
[_player play];
I like simple code and here is my solution : (Remember to add switch button to get music play. Have fun)
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#interface ViewController ()
{
NSURL* bgURL;
AVAudioPlayer* bgPlayer;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
bgURL = [[NSURL alloc] initFileURLWithPath: [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"mp3"]];
bgPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:bgURL error:nil];
}
#pragma mark AVAudioPlayer
- (IBAction)toggleMusic:(UISwitch*)sender {
NSLog(#"togging music %s", sender.on ? "on" : "off");
if (bgPlayer) {
if (sender.on) {
[bgPlayer play];
}
else {
[bgPlayer stop];
}
}
}
The Apple documentation here should have everything you need to know.
DIRAC API is free and quite easy to use.
We've used it in my talking robot app http://itunes.apple.com/us/app/daidai/id484833168 and it has been amazing to me how it manages to change the speed and pitch of voice
http://www.dspdimension.com/download/
The oalTouch sample code on the Apple iOS developer web site does what you want, and is ready to run.
It also shows how to test if another app (eg ipod) is playing a file already, which is handy if you want to allow your users to listen to their own music instead of yours.
Related
I am making an alarm app for iPhones and want to continuously loop the audio until the button is pressed again. As of now all it does is play the audio once when pressed. Here's the code:
-(IBAction)PlayAudioButton:(id)sender {
AudioServicesPlaySystemSound(PlaySoundID);
}
- (void)viewDidLoad {
NSURL *SoundURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"Sound" ofType:#"wav"]];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)SoundURL, &PlaySoundID);
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
Any suggestions?
Use AVAudioPlayer to play the sound. You must add AVFoundation.framework to your project for this to work. Start by declaring an AVAudioPlayer object. It must be declared either as a property with a strong attribute, e.g.
#property (strong, nonatomic) AVAudioPlayer *audioPlayer;
or as an instance variable with a __strong attribute
#interface Class : SuperClass //or #implementation Class
{
AVAudioPlayer __strong *audioPlayer;
}
Then, to load and play the file,
- (void)viewDidLoad
{
NSString *audioFilePath = [[NSBundle mainBundle] pathForResource:#"Sound" ofType:#"wav"];
NSURL *audioFileURL = [NSURL fileURLWithString:audioFilePath];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileURL error:nil];
audioPlayer.numberOfLoops = -1; //plays indefinitely
[audioPlayer prepareToPlay];
}
- (IBAction)PlayAudioButton:(id)sender
{
if ([audioPlayer isPlaying])
[audioPlayer pause]; //or "[audioPlayer stop];", depending on what you want
else
[audioPlayer play];
}
and, when you want to stop playing the sound, call
[audioPlayer stop];
I have executed the following code ,but sound is not working.
in .h
#import <AVFoundation/AVAudioPlayer.h>
#import <AVFoundation/AVFoundation.h>
in .m
NSString *soundPath = [[NSBundle mainBundle] pathForResource:#"sound1" ofType:#"mp3"];
NSURL *soundUrl = [NSURL fileURLWithPath:soundPath];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl];
[player play];
But I'm unable to hear any sound.Actually i wanted to manage button click sound along with volume button,so I'm using this method.
Did you set the volume?
[player setVolume:1.0];
Another way to play a short sound is AudioServicesCreateSystemSoundID.
See the link Play a short sound in iOS
Try with :
self.theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:(__bridge NSURL *)(soundUrl) error:NULL];
self.theAudio.volume = 1.0;
self.theAudio.delegate = self;
[self.theAudio prepareToPlay];
[self.theaudio play];
This works perfect for me.
Add AVFoundation and AudioToolBox frameworks into the project
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
#interface TestViewController : UIViewController
{
SystemSoundID SoundID;
}
#implementation TestViewController
-(void) viewDidLoad {
[super viewDidLoad];
NSURL *url = [[NSBundle mainBundle] URLForResource:#"test" withExtension:#"caf"];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &SoundID); //When using ARC, make sure to use __bridge
}
-(void) playSound {
AudioServicesPlaySystemSound(SoundID);
}
I have an iOS app which works like this:
First view
3 buttons that link to different views, each has its own audio file within
Imagine user opens one view, and starts to play the audio file. When they navigate around the app, the audio file still plays which is fine, Im happy with that.
However, if user then opens the second audio file and presses play, it plays on top of the first one so 2 audios are playing together.
How do I tell the code that if another play button is pressed it should stop the first audio file that is playing??
I am using AVFoundation framework to do this
Code is as follows:
NSString *stringPath = [[NSBundle mainBundle]pathForResource:#"01" ofType:#"MP3"];
NSURL *url = [NSURL fileURLWithPath:stringPath];
NSError *error;
avPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
[avPlayer setNumberOfLoops:2];
[avPlayer setVolume:self.sliderVolumeOutlet.value];
[NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:#selector(updateMyProgress) userInfo:nil repeats:YES];
-(void)updateMyProgress
{
float progress = [avPlayer currentTime]/[avPlayer duration];
self.myProgressView.progress = progress;
}
- (IBAction)sliderVolumeAction:(id)sender {
UISlider *mySlider = sender;
[avPlayer setVolume:mySlider.value];
}
- (IBAction)stopButton:(id)sender {
[avPlayer stop];
[avPlayer setCurrentTime:0];
}
- (IBAction)pauseButton:(id)sender {
[avPlayer pause];
}
- (IBAction)playButton:(id)sender {
[avPlayer play];
}
- (IBAction)backButtonEvent:(id)sender {
[self dismissViewControllerAnimated:YES completion:NULL];
}
You can check whether it is playing the previous track or not by if ([AVPlayer rate] != 0.0)
If it is playing then you can either add the next track into queue or just use this function to replace current track with the new one - (void)replaceCurrentItemWithPlayerItem:(AVPlayerItem *)item
Perhaps creating some sort of playSound function would be better suited for this. Something like this:
- (void)playSoundWithFileName:(NSString *)fileName andExtension:(NSString *)extension {
NSString *stringPath = [[NSBundle mainBundle]pathForResource:fileName ofType:extension];
NSURL *url = [NSURL fileURLWithPath:stringPath];
NSError *error;
if (avPlayer) {
[avPlayer stop];
avPlayer = nil;
}
avPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
if (error)
NSLog(#"Error");
else {
[avPlayer setNumberOfLoops:2];
[avPlayer setVolume:self.sliderVolumeOutlet.value];
[avPlayer play];
}
}
Use:
[self playSoundWithFileName:#"01" andExtension:#"MP3"];
[NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:#selector(updateMyProgress) userInfo:nil repeats:YES];
and call -(void)playSoundWithFileName whenever you want to play another sound.
Or if you were using the AVPlayer class:
- (void)playSoundWithFileName:(NSString *)fileName andExtension:(NSString *)extension {
NSString *stringPath = [[NSBundle mainBundle]pathForResource:fileName ofType:extension];
NSURL *url = [NSURL fileURLWithPath:stringPath];
AVPlayerItem *item = [AVPlayerItem playerItemWithURL:url];
if (avPlayer)
[avPlayer replaceCurrentItemWithPlayerItem:item];
else
avPlayer = [AVPlayer playerWithPlayerItem:item];
[avPlayer setVolume:self.sliderVolumeOutlet.value];
[avPlayer play];
}
Though the latter doesn't allow you set a number of loops.
I am developing an app in which user can select a sound file from device gallery and it will start playing in app background while app runs.
once selected it will run every time when app runs till user again browse and changes sound file.
do I need to copy sound file to app? or it can be done using its path only.
please let me know if anybody can help me.
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.
I did this as per my requirement you want to play it in background so you need to make some changes and play it in didFinishLaunchingWithOptions and stop it in applicationWillTerminate take into consideration this 2 methods too applicationDidEnterBackground applicationWillEnterForeground
#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
This is a newbie question.
I have a very simple app that is supposed to only play an audio file when a button on the main view is tapped.
I am using XCode version 4.6.
I added an audio file 'audioclip.wav' to my project. I have added the AVFoundation.framework.
My project only has ViewController.h and ViewController.m.
I double clicked and dragged from the button in the storyboard to the .h file using the assistant editor to create my IBAction connection.
My ViewController.h:
#import <UIKit/UIKit.h>
#import<AVFoundation/AVAudioPlayer.h>
#interface ViewController : UIViewController <AVAudioPlayerDelegate> {
}
- (IBAction)playAudio:(id)sender;
#end
My ViewController.m:
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)playAudio:(id)sender {
AVAudioPlayer *audioPlayer;
NSString *audioPath = [[NSBundle mainBundle] pathForResource:#"audioclip" ofType:#"wav" ];
NSURL *audioURL = [NSURL fileURLWithPath:audioPath];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:nil];
[audioPlayer play];
}
#end
For whatever reason (probably something silly I left out) The audioclip.wav file does not play when I click the button. I have tested on the iPhone 6.1 simulator and on my device.
I think there is some problem with wav files. Some people seem to get it to work, but I've tried several different files and none of them play. The mp3 and m4a files that are commented out in the code below worked fine. There's no need to do anything with a delegate, it's optional.
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#interface ViewController ()
#property (strong,nonatomic) AVAudioPlayer *audioPlayer;
#end
#implementation ViewController
- (IBAction)playAudio:(id)sender {
//NSString *audioPath = [[NSBundle mainBundle] pathForResource:#"11 Prayer" ofType:#"mp3" ];
//NSString *audioPath = [[NSBundle mainBundle] pathForResource:#"Sunshine" ofType:#"m4a" ];
NSString *audioPath = [[NSBundle mainBundle] pathForResource:#"space" ofType:#"wav" ];
NSURL *audioURL = [NSURL fileURLWithPath:audioPath];
NSError *error;
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&error];
[self.audioPlayer play];
}
If I log the error, with the wav file I get:
Error Domain=NSOSStatusErrorDomain Code=1685348671 "The operation couldn’t be completed. (OSStatus error 1685348671.)"
Please try to use this one..
- (IBAction)playAudio:(id)sender
{
NSURL *url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"audioclip" ofType:#"wav"]];
NSData *data =[NSData dataWithContentsOfURL:url];
audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:nil];
audioPlayer.delegate = self;
[audioPlayer setNumberOfLoops:0];
[audioPlayer play];
}
i hope this will help u
try like this ,
NSString *audio=[[NSBundle mainBundle]pathForResource:#"audioclip" ofType:#"wav"];
NSURL *url=[[NSURL alloc]initFileURLWithPath:audio];
avPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
avPlayer.delegate = self;
[avPlayer prepareToPlay];
[avPlayer play];
and once check IBOutlet connected or not and check the button action method with breakpoints.
As i can see you have made the code quite simple, so the way it's made does require that it is not a big wav file.
And by that you need to cut down the audio file to something like 10 seconds and under.
I was using the .m4a when I encountered this problem. For me, not implementing AVAudioSession was the issue
var session = AVAudioSession.sharedInstance()
do {
session.setCategory(AVAudioSessionCategoryPlayAndRecord)
try session.setActive(true)
} catch {
gf.displayAlert("problem encountered", userMessageTitle: "")
self.navigationController?.popViewControllerAnimated(true)
}