AVAudioPlayer iOS no sound - objective-c

Seems to be similar questions asked but none of the solutions seem to work for me. Cant for the life of me understand why my code doesnt work so here it is.
I dont get any errors but also get no sound.
#interface MainApp ()
#property (strong, nonatomic) AVAudioPlayer *audioPlayer;
-(void)playSoundFX:(NSString*) soundFile;
#end
#implementation MainApp
- (void)viewDidLoad {
[super viewDidLoad];
// Play sound
[self playSoundFX:#“sound.mp3"];
}
// Play sound
- (void)playSoundFX:(NSString*)soundFile {
// Setting up path to file url
NSBundle* bundle = [NSBundle mainBundle];
NSString* bundleDirectory = (NSString*)[bundle bundlePath];
NSURL *url = [NSURL fileURLWithPath:[bundleDirectory stringByAppendingPathComponent:soundFile]];
// Make an audioPlayer object and play file
NSError *error;
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
[audioPlayer setVolume:100.0f];
if (audioPlayer == nil)
NSLog(#"%#", [error description]);
else
[audioPlayer play];
}
#end
*********vvvvvvvvv Amended Code that works vvvvvvvvv**********
#interface MainApp ()
#property (strong, nonatomic) AVAudioPlayer *audioPlayer;
-(void)playSoundFX:(NSString*) soundFile;
#end
#implementation MainApp
- (void)viewDidLoad {
[super viewDidLoad];
// Play sound
[self playSoundFX:#“sound.mp3"];
}
// Play sound
- (void)playSoundFX:(NSString*)soundFile {
// Setting up path to file url
NSBundle* bundle = [NSBundle mainBundle];
NSString* bundleDirectory = (NSString*)[bundle bundlePath];
NSURL *url = [NSURL fileURLWithPath:[bundleDirectory stringByAppendingPathComponent:soundFile]];
// Make an audioPlayer object and play file
NSError *error;
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
[self.audioPlayer setVolume:100.0f];
if (self.audioPlayer == nil)
NSLog(#"%#", [error description]);
else
[self.audioPlayer play];
}
#end

I am execute your code on my iPhone. It is work properly.Please Select a device and run your code. I hope it will execute properly with sound.

You got to segregate the functionalities..
Loading audio file in viewDidLoad and play it on play action, some thing like this
#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:#"%#/sound.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];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)playSoundTapped:(id)sender
{
// When button is tapped, play sound
[_audioPlayer play];
}

Related

Impossible to play a video with AVPlayer

I've been through all the posts in StackOverflow but I can't get a full example of how to get a video from the bundle and reproduce it in a controller.
I've tried many things but my screen appeared blank or black.
In the last amend, my video remains like this:
no error is thrown on the log. This is my code:
.h (please ignore the name of the controller, it will be finally a camera)
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>
#interface NativeCameraViewController : UIViewController
#end
.m
#import "NativeCameraViewController.h"
#interface NativeCameraViewController ()
#property (nonatomic, retain) AVPlayerViewController *avPlayerViewcontroller;
#end
#implementation NativeCameraViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIView *view = self.view;
NSString *stringPath = [[NSBundle mainBundle]pathForResource:#"video" ofType:#"mov"];
NSURL *fileURL = [NSURL fileURLWithPath:stringPath];
AVPlayerViewController *playerViewController = [[AVPlayerViewController alloc] init];
playerViewController.player = [AVPlayer playerWithURL:fileURL];
self.avPlayerViewcontroller = playerViewController;
[self resizePlayerToViewSize];
[view addSubview:playerViewController.view];
view.autoresizesSubviews = TRUE;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void) resizePlayerToViewSize
{
CGRect frame = self.view.frame;
NSLog(#"frame size %d, %d", (int)frame.size.width, (int)frame.size.height);
self.avPlayerViewcontroller.view.frame = frame;
}
#end
and that's what I've got so far.
My video is correctly on the Bundle, called video.mov:
I've tried both linking and copying. Same result.
What am I doing wrong??
Thank you very much in advance.
I'd like to avoid using MPMoviePlayerController since it's deprecated in iOS9
It was actually my fault...
I was trying to reproduce an alias.
When you have 20.000 videos and 30.000 resources this things happen.
Instead of using AVPlayer, use MPMoviePlayerController class:
NSString *path = [[NSBundle mainBundle] pathForResource:#"video" ofType:#"mov"];
NSURL *url = [NSURL fileURLWithPath:path];
MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:url];
[player play];

- (BOOL)webview: doesn't run in objective c xcode

I am trying to get this to run... I have put in NSLogs, but nothing appears in the debugger when I change page.
Here is my code:
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize webview;
- (void)viewDidLoad
{
[super viewDidLoad];
self.webview.delegate = self;
NSString *path = [[NSBundle mainBundle] pathForResource:#"menu" ofType:#"html" inDirectory:#"pages"];
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webview loadRequest:request];
NSLog(#"%#",[[request URL] absoluteString]); //this log appears when the ipad simulator starts
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
This section below doesn't seem to run (no log appears in the debugger!)
- (BOOL)webview:(UIWebView*)aWebView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
NSLog(#"%#",[[request URL] absoluteString]);
NSString *absoluteUrl = [[request URL] absoluteString];
if ([absoluteUrl isEqualToString:#"didtap://button1"]) {
NSLog(#"Button tapped");
return NO;
}
return YES;
}
Check the capitalization of your delegate method; it should be:
- (BOOL)webView:(UIWebView*)aWebView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
i.e. webView, not webview.

Stopping sound in Xcode

Hi all,
Please look at the code below, i want to be able to stop the sound when the same button is clicked, another button is clicked and even when going back to the home screen. Not sure what to do here,
FoxViewController.m
#import "FoxViewController.h"
#import <AVFoundation/AVAudioPlayer.h>
AVAudioPlayer *newPlayer_Fox;
#interface FoxViewController ()
#end
#implementation FoxViewController
-(IBAction) Fox;
{
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: #"new"ofType: #"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: nil];
[newPlayer play];
}
- (id)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
FoxViewController.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
AVAudioPlayer *newPlayer;
#interface FoxViewController : UIViewController
-(IBAction)Fox;
#end
Your help is much appreciated, Justin.
Maintain one flag say BOOL soundPlay as global variable in FoxViewController.h file
Now in FoxViewController.m's viewDidLoad method
soundPlay = TRUE;
Action button will be like this:
-(IBAction) Fox;
{
if(soundPlay){
soundPlay = FALSE; //made false for next time another condition will be used.
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: #"new"ofType: #"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: nil];
[newPlayer play];
}
else
{
if([newPlayer isPlaying])
{
[newPlayer stop];
}
}
}
For stopping sound in background add this method if not added
-(void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
//stop background sound
if([newPlayer isPlaying])
{
[newPlayer stop];
}
}
Summarizing, the sentence to STOP the sound file is:
AudioServicesDisposeSystemSoundID (soundFileObject);
Explanation (Important to understand):
I have a table view with 18 different sound files. When user select a row must sound the corresponding file and when select another row, it must STOP the previous sound and play other.
All this stuff it is necessary:
1) Add to your project "AudioToolbox.framework" inside "Build Phases", inside "Link Binary With Libraries"
2) In header file (in my project it calls "GenericTableView.h") add these sentences:
#include <AudioToolbox/AudioToolbox.h>
CFURLRef soundFileURLRef;
SystemSoundID soundFileObject;
#property (readwrite) CFURLRef soundFileURLRef;
#property (readonly) SystemSoundID soundFileObject;
3) In implement file (in my project it calls "GenericTableView.m") add these sentences:
#synthesize soundFileURLRef;
#synthesize soundFileObject;
And inside your "Action" implementation or in my case, in:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
//
// That is the question: a way to STOP sound file
//
// -----------------------------------------------------------------------
// Very important to STOP the sound file
AudioServicesDisposeSystemSoundID (soundFileObject);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// In my project "rowText" is a field that save the name of the
// corresponding sound (depending on row selected)
// It can be a string, #"Alarm Clock Bell" in example
// Create the URL for the source audio file.
// URLForResource:withExtension: method is new in iOS 4.0.
NSURL *soundURL = [[NSBundle mainBundle] URLForResource:rowText withExtension:#"caf"];
// Store the URL as a CFURLRef instance
self.soundFileURLRef = (CFURLRef) [soundURL retain];
// Create a system sound object representing the sound file.
AudioServicesCreateSystemSoundID (soundFileURLRef,&soundFileObject);
AudioServicesPlaySystemSound (soundFileObject);
[soundURL release];
}
4) Finally, in the same implement file (in my project it calls "GenericTableView.m"):
- (void)dealloc {
[super dealloc];
AudioServicesDisposeSystemSoundID (soundFileObject);
//CFRelease (soundFileURLRef);
}
I must to comment "CFRelease (soundFileURLRef)" because the App ends unexpectedly when user leaves the table view.
All this code is proportioned by Apple. In this link you can find even a sample code to test directly in your iPhone simulator.
https://developer.apple.com/library/ios/samplecode/SysSound/Introduction/Intro.html#//apple_ref/doc/uid/DTS40008018-Intro-DontLinkElementID_2

can't play sound on Xcode 4.3

I am using Xcode 4.3 and i have a problem with playing sound...
I downloaded this project from an answer i found here from but when i change his file with mine http://dl.dropbox.com/u/63377498/AudioText.zip i can't hear anything. Can be a problem of my simulator? Settings of my mac? I don't know...
That's the code i use:
#interface ViewController ()
#property (nonatomic, strong) AVAudioPlayer *theAudio;
#end
#implementation ViewController
#synthesize theAudio = _theAudio;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *soundPath =[[NSBundle mainBundle] pathForResource:#"sad" ofType:#"caf"];
NSURL *soundURL = [NSURL fileURLWithPath:soundPath];
NSError *error;
self.theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:&error];
}
- (IBAction)pushBell {
[self.theAudio play];
}
Finally i found the answer on my own. I was doing everything right but i used a sound file downloaded from youtube in mp3 format and i converted to .caf format by changing the extension....Thats the reason why i can't play that sound!

Sound stops working in soundboard (Xcode)

In my soundboard app, after some time the sound will stop working until the app is closed and opened again. Can't figure out what is wrong! here is my code:
In the .h file :
(imported files here)
#interface MainView : UIView {
}
- (IBAction)pushButton2:(id)sender;
#end
In the .m file:
(imported files here)
#implementation MainView
- (IBAction)pushButton2:(id)sender {
NSString *path = [[NSBundle mainBundle] pathForResource:#"sound1" ofType:#"mp3"];
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
[theAudio play];
}
#end
I'm not sure it would cause the behavior you're seeing, but you're definitely leaking the AVAudioPlayer each time the button is pressed. Additionally, I would just load it once (say, in viewDidLoad), rather than on each button press. Perhaps something like:
#interface MainView : UIView
{
AVAudioPlayer* audioPlayer;
}
- (IBAction)pushButton2:(id)sender;
#end
#implementation MainView
- (void) viewDidLoad
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"sound1" ofType:#"mp3"];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
audioPlayer.delegate = self;
}
- (void) viewDidUnload
{
[audioPlayer release], audioPlayer = nil;
}
- (IBAction)pushButton2:(id)sender
{
[audioPlayer play];
}
#end